多个按钮触发单个jQuery函数

Multiple buttons to trigger single jQuery function

本文关键字:单个 jQuery 函数 按钮      更新时间:2023-09-26

我想使用多个图像来打开同一个jQuery对话框。我注意到这只适用于第一个图像,有没有办法让第二个图像也能工作,而不给它一个唯一的id?将有100多个这样的图像,所以我不想为每个图像创建新的功能

$(function() {
            $("#dialog").dialog({
                autoOpen: false},{ buttons: [ { text: "Ok", click: function() { $( this ).dialog( "close" ); } } ]});
            $("#IMG").on("click", function() {
                $("#dialog").dialog("open");
            });
        });
<div id="dialog" title="Dialog box">Test</div> 
<input type="image" id="IMG" src="img/image.gif">
<input type="image" id="IMG" src="img/image.gif">

为每个图像指定一个类,比如"img"。然后像这样声明一个处理程序:

$(".img").on("click", function() {
    $("#dialog").dialog("open");
});

ID必须是unqiue。改为使用类:

$(function() {
            $("#dialog").dialog({
                autoOpen: false},{ buttons: [ { text: "Ok", click: function() { $( this ).dialog( "close" ); } } ]});
            $(".open-img").on("click", function() {
                $("#dialog").dialog("open");
            });
        });

HTML:

<div id="dialog" title="Dialog box">Test</div> 
<input type="image" class="open-img" src="img/image.gif">
<input type="image" class="open-img" src="img/image.gif">