如何使这个函数运行不止一次JavaScript/jQuery

How to make this function run more than once JavaScript/jQuery

本文关键字:JavaScript jQuery 不止一次 运行 何使这 函数      更新时间:2023-09-26

我需要这段代码运行多次。只有当我单击按钮以附加图像,并单击按钮以删除它们时,它才运行。第三次点击不再追加图片

<button class="" onclick="showImages(this,'100000,jpg','1111111.jpg','5');"></button>
<div id="5" class="">
... //when I run the function it appends the <img> tag here
</div>
function showImages(button, image1, image2, id) { //user clicks a button "show"
    if (image2 == "") { //if there is only one image
        $('#show' + id + '').append('<img class='"one'" src='"images/' + image1 + ''" />'); //creates a div with 1 image
        button.onclick = function () { //clicks it second time
            $('#show' + id + '').empty(); //removes the div with image
        };
    } else { //if there are 2 images
        $('#show' + id + '').append('<img class='"two'" src='"images/' + image1 + ''" /><img src='"images/' + image2 + ''" />'); //div with 2 images
        button.onclick = function () { //...
            $('#show' + id + '').empty(); //...
        };
    }
}

既然你编辑了你的帖子,最好是给你另一个答案。通过此onclick="showImages(this,'100000,jpg','1111111.jpg','5');",您在按钮单击上附加了一个处理程序。之后在button.onclick = function () { $('#show' + id + '').empty(); };中,你又给了一个处理器。现在您有两个处理程序:一个显示图像,另一个立即杀死它。这就是为什么你的代码只工作一次(直到第二个处理程序没有绑定)。

让我们修复它。HTML:

<button id="my_button" image_1="10000.jpg" image_2="1111111.jpg" target_id="5"></button> <!-- move away javascript from HTML; put necessary data in button attributes -->
<div id="5">
...
</div>

和Javascript:

var toggleImages = function( event ){
  /* retrieve clicked button itself and all needed attributes */
  var button = $( event.target ),
      image_1 = "images/" + button.attr( 'image_1' ),
      image_2 = "images/" + button.attr( 'image_2' ),
      target = $( '#' + button.attr( 'target_id' ) );
  /* if no images shown – show it */
  if( 0 == target.find( 'img' ).length ){
    target.append( '<img src="' + image_1 + '" />' );
    if( 'undefined' != typeof image_2 ){
      target.append( '<img src="' + image_2 + '" />' );
    }
  /* if images was shown – remove it */
  } else {
    target.empty();
  }
}
$( '#my_button' ).on( 'click', toggleImages ); /* bind click handler only one time */