繁体   English   中英

JS。 以编程方式添加的Click事件,但在加载代码后仅触发一次

[英]Js. Click event added programmatically, but fires only once, when code is loaded

我正在使用JS / jQuery动态创建n个按钮,并且正在动态添加按钮单击事件。

问题是,当调用函数AddImageInTagTest()时,它将创建所有按钮并触发click事件,而无需我单击任何按钮。

另一个问题是,当我单击动态创建的按钮之一时,单击事件功能不会触发。

怎么会?

var count = 0;
function AddImageInTagTest(tagId, imageSrcPathAndimageFileName) {
    var fileNameWithExtension;

    fileNameWithExtension = imageSrcPathAndimageFileName.split("\\").pop(); //get just the filename with ext from the path
    $(tagId).html($(tagId).html() + "<img alt='' src='" +"\\" +imageSrcPathAndimageFileName +"'/>"+"<input id='Button"+count.toString()+"' type='button' value='delete image' />");
    $("#Button" + count.toString()).click(delete_image_custom());
    count++;
}

function delete_image_custom() {
    alert("Button is clicked");
}

我已经在click事件中更改并添加了匿名函数,但是单击时什么也没发生。

$("#Button" + count.toString()).click(function () { console.log("click event fired")});

我已将函数调用修改为:

$("#Button" + count.toString()).onClick(delete_image_custom); but nothing

由于您正在调用函数而不是辅助引用,因此会触发click事件。

$("#Button" + count.toString()).click(delete_image_custom());
                                                         ^^

()正在调用方法。 如果调用的方法将返回要执行的函数,则将执行此操作。 在您的情况下,您想分配一个引用,因此删除()

$("#Button" + count.toString()).click(delete_image_custom);

并且,当您添加新内容时,不应替换所有html。 使用append()将新元素添加到末尾。 当您替换html并将其重写时,将破坏元素及其事件处理程序。 追加不会这样做。

$(tagId).append("<img alt='' src='" +"\\" +imageSrcPathAndimageFileName +"'/>"+"<input id='Button"+count.toString()+"' type='button' value='delete image' />");

如果这么说,为什么不只使用事件委托呢?

$("#CommonParentElement").on("click", ".commonClassOnButton", function(){    
    var button = $(this);
    console.log(button);
});

这将消除在添加新元素时添加新事件的需要。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM