有没有一种方法可以选择单击时数组元素的索引?

时间:2019-10-20 13:41:41

标签: javascript html arrays indexof

我正在努力选择单击数组中元素的特定索引。这就是代码的和平,在此先感谢!

<div>

 <span class="dot"></span>
 <span class="dot"></span> -- lets say we click on this span
 <span class="dot"></span>
 <span class="dot"></span>
 <span class="dot"></span>

</div>



var dots = document.querySelectorAll(".dot");
for(var i = 0; i < dots.length; i ++){
dots[i].addEventListener("click", function(){
console.log(this) -- prints the actual html <span class="dot"></span>

// ?? How to print index of an element? To be more specific, in this case 
just "1" ??

})
}

5 个答案:

答案 0 :(得分:2)

由于向每个元素添加了事件侦听器,因此您可以console.log i的值。

注意:我在for循环中使用let i而不是var i,因为let使i的作用域为已阻止,并且在事件处理程序中保留当前的i值。

const dots = document.querySelectorAll(".dot");
for (let i = 0; i < dots.length; i++) {
  dots[i].addEventListener("click", function() {
    console.log({ i });
  })
}
<div>

  <span class="dot">1</span>
  <span class="dot">2</span>
  <span class="dot">3</span>
  <span class="dot">4</span>
  <span class="dot">5</span>

</div>

答案 1 :(得分:2)

实现此目的的一种方法是在您的 dot 中添加一个属性(我将其命名为 dotIndex ),然后console.log此属性。

array(3) { [0]=> string(4) "tag1" [1]=> string(7) "zamalek" [2]=> string(4) "ahly" }

检查小提琴:https://jsfiddle.net/254uqtm0/

但是,正如Ori Drori所建议的那样,您只需在循环中将 var 更改为 let 即可。如果您对为什么感到困惑,请检查以下线程:What's the difference between using "let" and "var"?

答案 2 :(得分:1)

您只需要一个事件侦听器(event delegation)。处理程序可以遍历现有元素并对其索引进行操作。像这样:

const log = (...things) => { 
  console.clear(); 
  things.forEach(thing => console.log(thing))
};

// iterate within the handler
document.addEventListener("click", showIndex);

// alternative: add a dataset value to the elements on page load
// and make the handler do something with that. This is static and
// can't be used if the number of .dott-elements changes dynamcally
Array.from(document.querySelectorAll(".dott")).forEach( (el, i) => el.dataset.index = i);
document.addEventListener("click", alternativeShowIndex);

function showIndex(evt) {
  if (evt.target.matches(".dot")) {
    let currentDot = {};
    const allDots = Array.from(document.querySelectorAll(".dot"));
    for (let i = 0; i < allDots.length; i += 1) {
      if (allDots[i] === evt.target) {
        currentDot = {index: i, text: allDots[i].textContent};
        break;
      }
    }
    log(currentDot);
  }
}

function alternativeShowIndex(evt) {
  evt.target.matches(".dott") && log(evt.target.dataset.index);
}
<div>
 <span class="dot">first</span>
 <span class="dot">second</span>
 <span class="dot">third</span>
 <span class="dot">fourth</span>
 <span class="dot">fifth</span>
</div>

<div>
 <span class="dott">alt-first</span>
 <span class="dott">alt-second</span>
 <span class="dott">alt-third</span>
 <span class="dott">alt-fourth</span>
 <span class="dott">alt-fifth</span>
</div>

答案 3 :(得分:1)

您可以这样做

const spans = [...document.getElementsByClassName('dot')];
spans.forEach(i => i.addEventListener('click', () => console.log(spans.indexOf(i))));

答案 4 :(得分:0)

您可以这样做

def send_mail_queue(subject, html_content, to_address, files=None):
    from mailqueue.models import MailerMessage

    try:
        new_message = MailerMessage()
        new_message.subject = subject
        new_message.to_address = to_address
        new_message.from_address = settings.DEFAULT_FROM_EMAIL
        new_message.html_content = html_content
        if files:
            # add attach file
            for file in files:
                attach_file = File(open(file, "rb"))
                new_message.add_attachment(attach_file)
        new_message.save()

    except Exception as ex:
        import logging
        logger = logging.getLogger(__name__)
        logger.error(ex)
        pass
var dots = [...document.getElementsByClassName('dot')];

for (let i=0; i<dots.length; i++) {
	dots[i].addEventListener("click", () => {
  	console.log(i);
  });
}