如何使这个函数运行不止一次JavaScript/jQuery
How to make this function run more than once JavaScript/jQuery
我需要这段代码运行多次。只有当我单击按钮以附加图像,并单击按钮以删除它们时,它才运行。第三次点击不再追加图片
<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 */
相关文章:
- 动态地改变“”的URL;添加新项目”;链接使用javascript/jquery
- Javascript(jQuery)给了我奇怪的结果
- 为什么不是't窗口.恢复正常工作吗?(javascript/jquery)
- Javascript/jQuery中的并行Ajax调用
- 我可以在Javascript/jQuery中使用一个变量作为键吗
- Javascript/Jquery/PHP加载页面-如何
- Javascript/Jquery Blob not showing Chrome PDF
- 如何使用javascript/jquery获取iframe的URL的锚点属性
- OnClick/Onhover Javascript/jquery
- 如何从javascript/jquery中的复选框中获取布尔值
- javascript/jquery将utc转换为短格式的本地时间
- 在不设置协议的情况下,使用javascript/jquery更改iframe-src
- 如何向这个javascript/jquery函数添加参数
- 用JavaScript/jQuery点击图片,选中多个方框
- 使用Javascript/JQuery获取JSON GET数据
- 从数组中删除元素的最佳方法是:javascript/jquery
- Javascript/jQuery压缩一个图像正确的评论帖子,并使用Ajax Laravel 5.2保存到控制器中
- 用DRY方式Javascript/JQuery动态替换HTML
- 类似Javascript JQuery的库
- 如何在 Javascript/jQuery 中获取一些随机下拉列表的选定值