admin管理员组文章数量:1403500
how do I know if an element of a list was clicked in javascript?
<div id="list">
<a href="#">one</a>
<a href="#">two</a>
<a href="#">three</a>
</div>
with Jquery is:
$('#list a')
JavaScript and how do I do?
how do I know if an element of a list was clicked in javascript?
<div id="list">
<a href="#">one</a>
<a href="#">two</a>
<a href="#">three</a>
</div>
with Jquery is:
$('#list a')
JavaScript and how do I do?
Share Improve this question asked Apr 2, 2014 at 0:28 Emerson BarcellosEmerson Barcellos 1613 silver badges6 bronze badges1 Answer
Reset to default 8You can use delegated event handling that takes advantage of event propagation so you put one event handler on the parent and it sees all the events from the children:
document.getElementById("list").addEventListener("click", function(e) {
// e.target will be the item that was clicked on
e.target.style.color = "#F00";
})
Or, you could attach an event handler to each link directly by enumerating the links that are children of the list:
var links = querySelectorAll("#list a");
for (var i = 0; i < links.length; i++) {
links[i].addEventListener("click", function(e) {
this.style.color = "#F00";
})
FYI, if programming in plain javascript, I find it very useful to use a few utility functions that help you iterate lists of HTML objects which are often returned from DOM functions:
// do a querySelectorAll() and then call a function on each item
// the parent argument is optional (defaults to document)
function iterateQuerySelectorAll(selector, fn, parent) {
parent = parent || document;
var items = parent.querySelectorAll(selector);
for (var i = 0; i < items.length; i++) {
fn(items[i]);
}
}
// add an event handler to each item that matches a selector
// the parent argument is optional (defaults to document)
function addEventQuerySelectorAll(selector, event, fn, parent) {
iterateQuerySelectorAll(selector, function(item) {
item.addEventListener(event, fn);
}, parent);
}
Then, with these utility helpers, the second example of code above would simply be this:
addEventQuerySelectorAll("#list a", "click", function() {
this.style.color = "#F00";
});
本文标签: htmlHow to tell if an element of a list was clicked in javascriptStack Overflow
版权声明:本文标题:html - How to tell if an element of a list was clicked in javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744383007a2603598.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论