我正在构建一个允许用户向数组中添加成分的应用程序。同时将项目添加到UI以供用户查看。在附加到DOM中,我添加了一个名为“data-item-index”的属性。当用户点击该订单项时,我希望JS能够读取“data-item-index”的值,以便我可以拼接该项的数组。现在,无法检测到li上的点击。可能是因为它不是原始DOM的一部分。我们怎么做这种事情。与JS稍后添加的DOM元素交互。
仅供参考,在代码中,我只是使用数字“3”作为索引进行测试。
ingredient_list = [];
yummly_search = "";
$(".ingredient").click(function() {
// alert("You clicked on" + $(this).attr('data-item-name') );
var new_ingredient = $(this).attr('data-item-name');
ingredient_list.push(new_ingredient);
console.log(ingredient_list);
// Add to the Yummly api call string
yummly_search = yummly_search.concat(new_ingredient + "+");
console.log(yummly_search);
// Show new ingredient in UI
$("#ingredients-list").append("<li class='shopping_list' data-item-index='3'>" + new_ingredient + "</li>");
});
// Remove from ingredient list
$(".shopping_list").click(function() {
var x = $(this).attr('data-item-index');
console.log(x);
ingredient_list.splice(x,1);
console.log(ingredient_list);
})
答案 0 :(得分:0)
动态添加的元素需要使用jQuery'on'而不是'click'。
$(document).on('click', '.ingredient', function(){
});