jQuery单击Appended Element不起作用 [英] jQuery click on Appended Element not working
问题描述
我有一个数组。我从Array获取数据并在jQuery Append to list中使用它。但是,当我点击列表项时,它只显示最后一个元素。
I have an array. I am getting data from Array and using it in jQuery Append to list. But when I am clicking on list item its only showing the last element.
var array = [[1,2,7],[3,4,8],[5,6,9]];
for (var i = 0; i < array.length; i++){
var firstVal = array[i].[0];
var secondVal = array[i].[1];
var thirdVal = array[i].[2];
var list = "<div class='divClass' <p class='class1'>"+ firstVal +"</p>"
+ "<p class='class2'>"+ secondVal +"</p></div>";
$("#myDiv").append(list);
$(".divClass").on('click', function(){
alert(thirdVal);
})
}
当我点击每个项目时,它总是显示 thirdVal
的最后一个值9.如何动态获取第三个值?
When I am clicking on each item it always shows the last value of thirdVal
that is 9. How can I get the Third value dynamically?
推荐答案
将事件处理程序移到之外
使用 .data(key,value)
循环并使用元素保存任意数据,稍后可以使用 .data重试当前元素上下文中的(键)
。
Move the event handler outside the for
loop and persist the arbitrary data with element using .data(key, value)
which can later be retried using .data(key)
in the current element context.
此外,检索数组元素时出现语法错误
Additionally, You have syntax error while retrieving array elements
var array = [
[1, 2, 7],
[3, 4, 8],
[5, 6, 9]
];
for (var i = 0; i < array.length; i++) {
//Rectify syntax errors while reading
var firstVal = array[i][0];
var secondVal = array[i][1];
var thirdVal = array[i][2];
var list = "<div class='divClass'><p class='class1'>" + firstVal + "</p>" + "<p class='class2'>" + secondVal + "</p></div>";
$(list).data('item', thirdVal).appendTo("#myDiv");
}
$(".divClass").on('click', function() {
console.log($(this).data('item'));
})
.divClass {
border: 1px solid black
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='myDiv'></div>
或者,使用让
而不是 var
并将元素处理程序绑定到元素然后将其附加到列表。一个很好的阅读使用之间有什么区别"让"和var申报变量?
Or, use let
instead of var
and bind element handler to element then append it to list. A good read What's the difference between using "let" and "var" to declare a variable?
var array = [
[1, 2, 7],
[3, 4, 8],
[5, 6, 9]
];
for (var i = 0; i < array.length; i++) {
//Rectify syntax errors while reading
var firstVal = array[i][0];
var secondVal = array[i][1];
let thirdVal = array[i][2];
var list = "<div class='divClass'><p class='class1'>" + firstVal + "</p>" + "<p class='class2'>" + secondVal + "</p></div>";
$(list).on('click', function() {
console.log(thirdVal);
}).appendTo("#myDiv");
}
.divClass {
border: 1px solid black
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='myDiv'></div>
这篇关于jQuery单击Appended Element不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!