gpt4 book ai didi

javascript - jquery中json循环后的命令

转载 作者:行者123 更新时间:2023-12-03 03:40:10 25 4
gpt4 key购买 nike

我的 jquery 有问题,当页面加载时,我调用一个 json 文件并循环遍历它的项目。但我无法将任何事件监听器附加到添加的输入按钮。

例如,我想做一条警报消息..

我想我不能通过jquery选择输入按钮

    $.getJSON("data.json", function(json) {
var html = "";
json['products'].forEach(function(val){
var location = '"?id='+val.id+'"';
html += "<div class='item'>"
html += "<div class='item-header'>";
html += "<h3>" + val.item_name + "</h3></div>";
html += "<div class='item-img'>";
html += "<img src='http://www.safensound.com.my/public/images/no_product_img.jpg' title=" + val.item_name + "></img></div>"
html += "<div class='item-footer'>";
html += "<p>Country: " + val.country_of_origin + "</p>";
html += "<p>Price: " + val.price + " $</p>";
html += "<input type='button' data-id='"+val.id+"' class='btn btn-success' value='Add to cart'></input>";
html += "</div></div>";
});

$(".items").html(html);
});

这是 onclick 命令:

$("item-footer>input[type='button']").on("click", function(){
alert("Hi");
});

最佳答案

对于动态创建的元素,您至少需要有一个静态元素,该元素是其他元素的父元素:

$("#SOME_STATIC_PARENT").on("click",".item-footer>input[type='button']", function(){
alert("Hi");
});

在您的示例中,.items 可能很好,所以:

$(".items").on("click",".item-footer>input[type='button']", function(){
alert("Hi");
});

关于javascript - jquery中json循环后的命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45663415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com