gpt4 book ai didi

javascript - 如何在 JSON 成功时添加 JS 事件

转载 作者:行者123 更新时间:2023-12-02 14:51:58 25 4
gpt4 key购买 nike

我的Code-igniter View 具有AJAX数据,如下所示。 DIV article-data DIV 的内容列表。(工作完美)现在我想将每个 DIV 作为一个按钮以及放置按钮单击事件的位置。我在哪里放置以下代码。

$(".target").click(function () {

});

JS

$(window).load(function() {
$.ajax({
url: '<?php echo base_url(); ?>' + 'main/data',
dataType: "JSON",
type: "POST",
success: function(retdata) {
$.each(retdata, function(i) {
var content = '<div class="target btn-default">' + retdata[i].content + '</div>';
$(".article-data").append(content); //line 23

});
}
});
});
<div class="article-data">

</div>

最佳答案

您应该使用Event Delegation使用.on()动态生成元素时的委托(delegate)事件方法。您不需要在 success block 中绑定(bind)事件。

The delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.

一般语法

$(document).on('event','selector',callback_function)

您应该使用最接近的静态容器来代替文档

示例

$(function() {
$(".article-data").on('click', ".target", function() {
//Your code
});
})

$(function() {
$(".article-data").on('click', ".target", function() {
//Your code
});
})


$(window).load(function() {
$.ajax({
url: '<?php echo base_url(); ?>' + 'main/data',
dataType: "JSON",
type: "POST",
success: function(retdata) {
$.each(retdata, function(i) {
var content = '<div class="target btn-default">' + retdata[i].content + '</div>';
$(".article-data").append(content); //line 23

});
}
});
});
<div class="article-data">

</div>

一本好书Direct and delegated events

关于javascript - 如何在 JSON 成功时添加 JS 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36126605/

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