свяжите номер с каждой ссылкой html, используя javascript - PullRequest
0 голосов
/ 13 июля 2020

Я хочу присвоить каждой ссылке, выбранной из DOM, номер, используя js. Для этого я сделал функцию, используя метод карты, чтобы связать все ссылки с ключом

function mapLinks(){
    var links = document.querySelectorAll('a')
    var listLinks = new Array(links.length); 
    for(i = 0; i <links.length; i++){
        listLinks[i] = i; 
    }
    var mapLink = new Map([[listLinks, links]]) 
    return (mapLink)
}
var map = mapLinks(); 
теперь, что я хочу сделать, это показать числа (или клавиши) на веб-странице, примерно так:

image

function linksNumber(){ 
    for(var [key, value] of map){
        for(var i = 0, j = 0; i < key.length, j < value.length; i++, j++){
            value[j].textContent = value[j].textContent + key[i]
        }
    }
}

Ответы [ 3 ]

2 голосов
/ 13 июля 2020

Вы можете использовать селектор css ::before или ::after с content: attr(data-n), чтобы структура страницы оставалась в основном такой же.

function mapLinks(){
    var links = document.querySelectorAll('a')
    var listLinks = new Array(links.length); 
    for(i = 0; i <links.length; i++){
        links[i].setAttribute('data-n', i)
    }
    var mapLink = new Map([[listLinks, links]]) 
    return (mapLink)
}

mapLinks()
a::after {
  content: attr(data-n);
  width: 10px;
  height: 10px;
  background: yellow;
  display: inline;
  font-size: 10px;
  position: relative;
  top: -6px;
}
<a href="test">Test</a>
<a href="hi">Hi</a>

Если вы не можете добавить файл css, вы можете использовать JS, чтобы добавить встроенный <style> элемент:

var sheet = document.createElement('style');
sheet.innerHTML = `
  a::after {
    content: attr(data-n);
    width: 10px;
    height: 10px;
    background: yellow;
    display: inline;
    font-size: 10px;
    position: relative;
    top: -6px;
  }
`
(document.head || document.getElementsByTagName('head')[0]).appendChild(sheet);

Или без javascript, кроме создания таблицы стилей:

var sheet = document.createElement('style');
sheet.innerHTML = `
      body { counter-reset: number -1; }
      a::after {
        content: counter(number);
        counter-increment: number;
        width: 10px;
        height: 10px;
        background: yellow;
        display: inline;
        font-size: 10px;
        position: relative;
        top: -6px;
      }
    `;
(document.head || document.getElementsByTagName('head')[0]).appendChild(sheet);
<a href="hello">Hello</a>
<a href="world">World</a>
0 голосов
/ 13 июля 2020

Осторожно с этим:

var links = document.querySelectorAll('a')

Если у вас будет больше <a /> в будущем, он также их заберет. Я рекомендую добавить класс к элементам (<a/>), которые вы хотите отметить.

Допустим, мы добавляем класс «anchorTooltip» ко всему, что вам нужно.

var links = document.querySelectorAll('a.anchorTooltip')

Это примет все якоря с классом anchorTooltip

Теперь вы можете:

Array.from(links).map((link, index)=>link.setAttribute("title", index))

querySelectorAll() возвращает stati c (не активный) NodeList, представляющий список документов элементы, соответствующие указанной группе селекторов. Используйте Array.from() для преобразования NodeList в массив, затем выполните итерацию по Array.map().

Тесты:

var links = document.querySelectorAll('a.anchorTooltip')

Array.from(links).map((link, index)=>link.setAttribute("title", index))
  <a class="anchorTooltip">test 1</a><br >
  <a class="anchorTooltip">test 2</a><br >
  <a class="anchorTooltip">test 3</a>

Без Array.from ():

document.querySelectorAll('a.anchorTooltip').forEach((link, index)=>link.setAttribute("title", index+40))

Тест:

document.querySelectorAll('a.anchorTooltip').forEach((link, index)=>link.setAttribute("title", index+10))
  <a class="anchorTooltip">test 1</a><br >
  <a class="anchorTooltip">test 2</a><br >
  <a class="anchorTooltip">test 3</a>
0 голосов
/ 13 июля 2020

Использование .map() здесь излишне. .querySelectorAll() возвращает объект, подобный массиву, который вы можете перебирать, используя .forEach(), и получать индекс из.

Все, что вам действительно нужно сделать в l oop, - это просто создать новый элемент, который будет содержать значение «значка». Большая часть работы фактически находится в CSS, а не в JavaScript.

См. Встроенные комментарии:

// Just loop over the collection returned by .querySelectorAll()
// with .forEach, which has a callback funciton that can provide
// you with the index.
document.querySelectorAll('a').forEach(function(link, index){
  let badge = document.createElement("span");
  badge.classList.add("badge");
  // Just use the index of the item you are iterating over
  badge.textContent = index + 1;
  link.appendChild(badge);
});
/* Giving the new elements this class
   will allow them to "float" above the
   link element they correspond to. You 
   can tweak the top and left values for
   better positioning. */
.badge {
  position:absolute; /* puts in own layer */
  display:inline-block; /* let's us style as a block */
  border:1px solid #808080;
  padding:2px;
  background: #ff7;
  border-radius:3px;
  font-size:.7em;
  top:-.8em;  /* Moves the element relative to the parent <a> */
  left:-.8em; /* Moves the element relative to the parent <a> */
}

/* Basic styling for the links */
a {
  position:relative; /* doesn't move them, but puts them in their own layer */
  text-decoration:none; /* no underline */
  display:block;
  margin:1em;
  height:50px;
  width:50px;
  border:#e0e0e0;
  background-color:#99f;
  padding:5px;
}
<a href="#one">One</a>  
<a href="#two">Two</a>  
<a href="#three">Three</a>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...