JQuery - 将 onclick 添加到动态生成的 img 标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/866252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:57:22  来源:igfitidea点击:

JQuery - Add onclick to dynamically generated img tag

jquery

提问by Peter

I am creating several image dynamically using the following code:

我正在使用以下代码动态创建多个图像:

function refresh_gallery(galleryidentifier, albumid) {
    $.ajax({ type: "POST", url: "/Photos/Thumbnails/" + albumid + "/", data: {}, success: function(msg) {
        try {
            var fotos = eval(msg); $(galleryidentifier).empty(); if (fotos.length == 0) { $(galleryidentifier).html("Press "Add files..." and select files to upload!"); return true; }
            for (var f in fotos) {
                //this image needs the onclick eventhandler
                $(document.createElement("img")).attr({ src: '/images/delete.gif', title: 'Delete ' + fotos[f].Title }).addClass("icon_delete").appendTo(galleryidentifier); ;
                $(document.createElement("img")).attr({ src: fotos[f].ThumbnailPath, title: fotos[f].Title }).addClass("thumbnail").appendTo(galleryidentifier);
            }
            var del_div = $(document.createElement("div")).css({ "padding": "4px" }).appendTo(galleryidentifier);
            var delete_span = $(document.createElement("span")).click(delete_files(albumid)).css({ "cursor": "pointer", "font-size": "12px" }).appendTo(del_div);
            $(document.createElement("img")).attr({ "src": "/Content/images/delete.png" }).appendTo(delete_span);
            $(document.createTextNode("delete all")).appendTo(delete_span);
            return true;
        }
        catch (e) {
            alert(e);
        }
        alert("Refresh error!");
    }, error: function() { alert("Refresh error!"); }
    });
}

The generation of the images is working fine, but I want to add an onclick eventhandler to the first image being generated (see comment in code). How do I do this? I'm fairly new to JQuery.

图像的生成工作正常,但我想在生成的第一个图像中添加一个 onclick 事件处理程序(请参阅代码中的注释)。我该怎么做呢?我对 JQuery 相当陌生。

Thanks!

谢谢!

回答by Nadia Alramli

$(document.createElement("img"))
    .attr({ src: '/images/delete.gif', title: 'Delete ' + fotos[f].Title })
    .addClass("icon_delete")
    .appendTo(galleryidentifier)
    .click(function(){
        // Do something
    })

回答by Andrew Noyes

jQuery has a method called click, the argument to which is a callback function. In this example, I'm also going to use a (much) simpler shorthand for creating an image element:

jQuery 有一个叫做 click 的方法,它的参数是一个回调函数。在这个例子中,我还将使用一个(非常)简单的速记来创建一个图像元素:

$('<img/>').click(function () {
    // do something
}).attr({
    src: '/images/delete.gif',
    title: 'Delete ' + fotos[f].Title
}).addClass("icon_delete").appendTo(galleryidentifier);

回答by hitautodestruct

Ever since jQuery 1.4 you can create an element and add all atrributes/events to it when creating.

从 jQuery 1.4 开始,您可以创建一个元素并在创建时向其添加所有属性/事件。

In the case of an image tag you would write:

在图像标签的情况下,你会写:

$('<img/>', {
    src:     '/images/delete.gif',
    title:   'Delete ' + fotos[f].Title,
    'class': 'icon_delete', // in quotes because class is a reserved js word
    click:   function( e ){
        // Everything here happens when you click the image.
    }
}).appendTo(galleryidentifier);

Above examplein JSBin.

上面的例子在 JSBin 中。

Here's the referenceto the docs.

这是对文档的参考

Why it's better than the other ways of creating an image using jQuery:

为什么它比使用 jQuery 创建图像的其他方式更好:

  • Much cleaner than chaining a dozen methods.
  • Allows you to send in objects with different properties to be created.
  • Matches up nicely with a regular html "Hard coded" element.
  • 比链接十几种方法要干净得多。
  • 允许您发送具有要创建的不同属性的对象。
  • 与常规的 html“硬编码”元素很好地匹配。

回答by Paul Morie

You can add an event handler of this type using the clickfunction in the same way you added the css class.

您可以按照添加 css 类的相同方式使用click函数添加这种类型的事件处理程序。

回答by Boris Guéry

you could just create a class when creating your image with addClass() method. And elsewhere have something like

您可以在使用 addClass() 方法创建图像时创建一个类。在其他地方有类似的东西

$(document).ready(
  $("img.toBeClicked").click(function() {
    //some code
  };
};