javascript 在javascript中为数组元素添加Click事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15739652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding Click event for Array Elements in javascript
提问by Arul Anthony
I am new to javascript I have a multi dimensional array which has 'li' in it. i want to add click event listener for all the li in my multidimensional array my array is like this
我是 javascript 新手,我有一个多维数组,其中包含“li”。我想为我的多维数组中的所有 li 添加单击事件侦听器我的数组是这样的
newItems = [
[li.pL14, li, li.pR15],
[li.pL14, li, li.pR15],
[li.pL14, li, li.pL14],
[li, li.pR15, li.description],
[li.pL14, li, li.pR15],
[li.pL14, li]
]
采纳答案by Prasath K
Try this ...Let your newItems is the MultiDimensional variable of element "li"
试试这个...让你的 newItems 是元素“li”的多维变量
for(var i=0;i<newItems.length;i++)
{
for(var j=0;j<newItems[i].length;j++)
{
newItems[i][j].addEventListener('click',function(){
// Your On Click code
},false);
}
}
回答by dfsq
Assuming that newItems
contains arrays of Nodes, not strings.
假设newItems
包含节点数组,而不是字符串。
Variant #1. Simple for loop
:
变体#1。简单for loop
:
for (var i = newItems.length; i--;) for (var j = newItems[i].length; j--;)
$(newItems[i][j]).click(function() {
// click
});
Demo: http://jsfiddle.net/ymuHR/
演示:http: //jsfiddle.net/ymuHR/
Variant #2*. Flatten array and convert into jQuery collection:
变体#2*。展平数组并转换为 jQuery 集合:
$([].concat.apply([], newItems)).click(function() {
alert(this.id);
});
回答by Murtaza Khursheed Hussain
Or you can use map function of jquery
或者你可以使用 jquery 的 map 功能
$.map( newItems , function( val, i ) {
$('#'+val).click(function(){
//do something.
});
});
I know its late. but it is new late for improvements. Regards
我知道已经晚了。但这是新的改进。问候
回答by user2737572
HTML
HTML
<div id="abc1"><a href="#">linl 01</a></div>
<div id="abc2"><a href="#">linl 02</a></div>
<div id="abc3"><a href="#">linl 02</a></div>
<div id="abc4"><a href="#">linl 02</a></div>
jQuery
jQuery
var ids = ["#abc1", "#abc2", "#abc3", "#abc4"];
for(var i=0;i<ids.length;i++) {
$(ids[i]).click(function(){
$(this).find("a").css({
'font-weight':'bold'
});
});
}