gpt4 book ai didi

javascript - 在动态添加的按钮上注册点击事件 jQuery

转载 作者:行者123 更新时间:2023-11-28 11:05:15 26 4
gpt4 key购买 nike

我正在使用 Bootstrap

以下是我的代码,用于动态获取提要,然后通过附加到 id 为“feeds”的分区内将它们添加到页面上:

$.ajax({
url: 'http://api.feedzilla.com/v1/categories/'+newsId+'/articles.json',
type: 'GET',
dataType: 'json',

// to execute when successfully got json response
success: function(response){
$.each(response.articles, function(){
var feed= "<div class='media well'>"+
"<div class='media-body'>"+
"<h4 class='media-heading'>"+this.title+"</h4>"+
"<h6>"+this.publish_date+"</h6>"+
"<p>"+this.summary+"</p>"+
"<a href='"+this.url+"' target='_blank'>Continue Reading</a>"+
"</div><br><br>"+
"<button class='showinfo btn pull-right' id='info'>Show Info</button>"+
"</div>";

$('#feeds').append(feed);
});
},

// to execute when error
error: function(jqXHR, textStatus, errorThrown){
alert("Server error!");
},

// execute at last whether success or error
complete: function(){

}
});

如您所见,我添加了一个“showinfo”类以及“info”id 来动态添加按钮。

现在以下是我的事件处理程序:

    // SHOW INFO BUTTON CLICK HANDLER
$('.showinfo').click(function(){
alert('triggered');
});

但它不起作用:(!! id: $('#info').click()!!如果我不动态添加按钮,它就可以完美工作。为什么会这样?

最佳答案

使用on() :

$('#feeds').on('click', '.showinfo', function() {
alert('triggered');
});

上面的代码绑定(bind)了 #feeds 内与 .showinfo 匹配的任何元素上的任何 click 事件。/strong> 到指定的回调函数。

另外,请注意,应该匹配的元素(在本例中是 .showinfo)不需要在绑定(bind)时存在(因此它适用于动态添加的元素,如好吧)。

关于javascript - 在动态添加的按钮上注册点击事件 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17274023/

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