I'm currently trying to write some JavaScript to get the attribute of the class that has been clicked. I know that to do this the correct way, I should use an event listener. My code is as follows:
我目前正在尝试编写一些JavaScript来获取已被单击的类的属性。我知道要以正确的方式执行此操作,我应该使用事件侦听器。我的代码如下:
var classname = document.getElementsByClassName("classname");
var myFunction = function() {
var attribute = this.getAttribute("data-myattribute");
alert(attribute);
};
classname.addEventListener('click', myFunction(), false);
I was expecting to get an alert box every time I clicked on one of the classes to tell me the attribute but unfortunately this does not work. Can anyone help please?
每次我点击其中一个类告诉我属性时,我都希望得到一个警报框,但遗憾的是这不起作用。有人可以帮忙吗?
(Note - I can quite easily do this in jQuery
but I would NOT like to use it)
(注意 - 我可以很容易地在jQuery中执行此操作,但我不想使用它)
3 个解决方案
#1
199
This should work. getElementsByClassName
returns an array Array-like object(see edit) of the elements matching the criteria.
这应该工作。 getElementsByClassName返回与条件匹配的元素的数组类似数组的对象(请参阅edit)。
var classname = document.getElementsByClassName("classname");
var myFunction = function() {
var attribute = this.getAttribute("data-myattribute");
alert(attribute);
};
for (var i = 0; i < classname.length; i++) {
classname[i].addEventListener('click', myFunction, false);
}
jQuery does the looping part for you, which you need to do in plain JavaScript.
jQuery为您完成循环部分,您需要在纯JavaScript中执行此操作。
If you have ES6 support you can replace your last line with:
如果您有ES6支持,可以用以下内容替换最后一行:
Array.from(classname).forEach(function(element) {
element.addEventListener('click', myFunction);
});
Note: Older browsers (like IE6, IE7, IE8) don´t support getElementsByClassName
and so they return undefined
.
注意:较旧的浏览器(如IE6,IE7,IE8)不支持getElementsByClassName,因此它们返回undefined。
EDIT : Correction
编辑:更正
getElementsByClassName
doesnt return an array, but a HTMLCollection in most, or a NodeList is some browsers (Mozilla ref). Both of these types are Array-Like, (meaning that they have a length property and the objects can be accessed via their index), but are not strictly an Array or inherited from an Array. (meaning other methods that can be performed on an Array cannot be performed on these types)
getElementsByClassName不返回数组,但大多数都是HTMLCollection,或NodeList是某些浏览器(Mozilla ref)。这两种类型都是Array-Like,(意味着它们具有length属性,并且可以通过索引访问对象),但不是严格的Array或从Array继承。 (意味着无法在这些类型上执行可在阵列上执行的其他方法)
Thanks to user @Nemo for pointing this out and having me dig in to fully understand.
感谢用户@Nemo指出这一点并让我深入了解。
#2
1
An alternative answer to add an event listener to a class where items are frequently being added and removed. This is inspired by jQuery's on
function where you can pass in a selector for a child element that the event is listening on.
将事件侦听器添加到经常添加和删除项的类的替代答案。这是受jQuery函数的启发,您可以在其中传入事件正在侦听的子元素的选择器。
var base = document.getElementById('base'); // the container for variable content
var selector = '.card'; // any css selector for children
base.addEventListener('click', function(event) {
if (event.target.matches(selector)) {
// handle class event
}
});
This will listen for clicks on children of the base
element and if the target of a click matches the selector, the class event will be handled. You can add and remove elements as you like without having to add more click listeners to the individual elements. This will catch them all even for elements added after this listener was added, just like the jQuery functionality (which I imagine is somewhat similar under the hood).
这将侦听对基本元素的子元素的单击,如果单击的目标与选择器匹配,则将处理类事件。您可以根据需要添加和删除元素,而无需向单个元素添加更多单击侦听器。即使对于添加此侦听器之后添加的元素,这也将捕获它们,就像jQuery功能(我想在引擎盖下有些类似)。
This depends on the events propagating, so if you stopPropagation
on the event somewhere else, this won't work. Also, the matches
function has some compatibility issues with IE apparently (what doesn't?).
这取决于传播的事件,所以如果你在其他地方停止传播事件,这将无法工作。此外,匹配功能显然与IE有一些兼容性问题(什么不是?)。
This could be made into a function if you need to do this repeatedly, like
如果您需要反复执行此操作,可以将其设置为函数,例如
function addChildEventListener(base, eventName, selector, handler) {
base.addEventListener(eventName, function(event) {
if (event.target.matches(selector)) {
// passes the event to the handler and sets `this`
// in the handler as the target element from the event
handler.call(event.target,event);
}
});
}
Fiddle: https://jsfiddle.net/u6oje7af/23/
小提琴:https://jsfiddle.net/u6oje7af/23/
#3
0
Always remember while using getElementsByClassName you must use loop to access the variables. Example:
始终记住在使用getElementsByClassName时,必须使用循环来访问变量。例:
var classname = document.getElementsByClassName("classname");
for(i=0;i<classname.length;i++){
classname[i].addEventListener('click', myFunction, false);
}
#1
199
This should work. getElementsByClassName
returns an array Array-like object(see edit) of the elements matching the criteria.
这应该工作。 getElementsByClassName返回与条件匹配的元素的数组类似数组的对象(请参阅edit)。
var classname = document.getElementsByClassName("classname");
var myFunction = function() {
var attribute = this.getAttribute("data-myattribute");
alert(attribute);
};
for (var i = 0; i < classname.length; i++) {
classname[i].addEventListener('click', myFunction, false);
}
jQuery does the looping part for you, which you need to do in plain JavaScript.
jQuery为您完成循环部分,您需要在纯JavaScript中执行此操作。
If you have ES6 support you can replace your last line with:
如果您有ES6支持,可以用以下内容替换最后一行:
Array.from(classname).forEach(function(element) {
element.addEventListener('click', myFunction);
});
Note: Older browsers (like IE6, IE7, IE8) don´t support getElementsByClassName
and so they return undefined
.
注意:较旧的浏览器(如IE6,IE7,IE8)不支持getElementsByClassName,因此它们返回undefined。
EDIT : Correction
编辑:更正
getElementsByClassName
doesnt return an array, but a HTMLCollection in most, or a NodeList is some browsers (Mozilla ref). Both of these types are Array-Like, (meaning that they have a length property and the objects can be accessed via their index), but are not strictly an Array or inherited from an Array. (meaning other methods that can be performed on an Array cannot be performed on these types)
getElementsByClassName不返回数组,但大多数都是HTMLCollection,或NodeList是某些浏览器(Mozilla ref)。这两种类型都是Array-Like,(意味着它们具有length属性,并且可以通过索引访问对象),但不是严格的Array或从Array继承。 (意味着无法在这些类型上执行可在阵列上执行的其他方法)
Thanks to user @Nemo for pointing this out and having me dig in to fully understand.
感谢用户@Nemo指出这一点并让我深入了解。
#2
1
An alternative answer to add an event listener to a class where items are frequently being added and removed. This is inspired by jQuery's on
function where you can pass in a selector for a child element that the event is listening on.
将事件侦听器添加到经常添加和删除项的类的替代答案。这是受jQuery函数的启发,您可以在其中传入事件正在侦听的子元素的选择器。
var base = document.getElementById('base'); // the container for variable content
var selector = '.card'; // any css selector for children
base.addEventListener('click', function(event) {
if (event.target.matches(selector)) {
// handle class event
}
});
This will listen for clicks on children of the base
element and if the target of a click matches the selector, the class event will be handled. You can add and remove elements as you like without having to add more click listeners to the individual elements. This will catch them all even for elements added after this listener was added, just like the jQuery functionality (which I imagine is somewhat similar under the hood).
这将侦听对基本元素的子元素的单击,如果单击的目标与选择器匹配,则将处理类事件。您可以根据需要添加和删除元素,而无需向单个元素添加更多单击侦听器。即使对于添加此侦听器之后添加的元素,这也将捕获它们,就像jQuery功能(我想在引擎盖下有些类似)。
This depends on the events propagating, so if you stopPropagation
on the event somewhere else, this won't work. Also, the matches
function has some compatibility issues with IE apparently (what doesn't?).
这取决于传播的事件,所以如果你在其他地方停止传播事件,这将无法工作。此外,匹配功能显然与IE有一些兼容性问题(什么不是?)。
This could be made into a function if you need to do this repeatedly, like
如果您需要反复执行此操作,可以将其设置为函数,例如
function addChildEventListener(base, eventName, selector, handler) {
base.addEventListener(eventName, function(event) {
if (event.target.matches(selector)) {
// passes the event to the handler and sets `this`
// in the handler as the target element from the event
handler.call(event.target,event);
}
});
}
Fiddle: https://jsfiddle.net/u6oje7af/23/
小提琴:https://jsfiddle.net/u6oje7af/23/
#3
0
Always remember while using getElementsByClassName you must use loop to access the variables. Example:
始终记住在使用getElementsByClassName时,必须使用循环来访问变量。例:
var classname = document.getElementsByClassName("classname");
for(i=0;i<classname.length;i++){
classname[i].addEventListener('click', myFunction, false);
}