gpt4 book ai didi

jquery - 如何防止按钮倍增?

转载 作者:行者123 更新时间:2023-12-01 03:41:14 24 4
gpt4 key购买 nike

我是一个完全的 jQuery 初学者,但是,我正在尝试创建一段代码,在单击缩略图时显示描述。我设法让它工作,以便它显示属于每张图片的尊重描述,并创建一个功能关闭按钮。

但是当我使用缩略图关闭描述时(使用了切换方法),如果我再次打开该图片的描述,该按钮会成倍增加。

我知道它会这样做,因为每次打开描述窗口时代码都会附加按钮,但不知道如何防止这种情况。我尝试寻找可能的解决方案,但没有找到与我的问题类似的任何内容。

这是我正在使用的 jQuery 代码:

$(document).ready(function() {
$('.thumbnails li img').click(function() {
var thumbSplit = $(this).attr('id').split('_');
identName = $('#cont_' + thumbSplit[1]);

identName.toggle();
$('.content-window').not(identName).hide();

var closeButton = $('<button class="close">close</div>');
closeButton.appendTo(identName.not(':hidden'));
closeButton.click(function() {
$(this).parents('.content-window').hide();
closeButton.remove();
});
});
});

这是一个 JSFiddle 链接:http://jsfiddle.net/thosetinydreams/4r8QP/4/

最佳答案

每次单击其中一张图像时,都会动态创建关闭按钮。有几种方法可以避免此问题。

  • 每次进入点击事件时,请先删除所有现有按钮,然后再添加按钮。
  • 不要动态添加按钮 - 只需将它们添加到 html 中。

我倾向于第二种,因为它更干净。

让我看看是否可以修复 fiddle ......

HERE是一个用于移动按钮的 fiddle 。我做了我提到的更改,并将 $('.close').click 函数移动如下:

$(document).ready(function() {
$('.thumbnails li img').click(function() {
var thumbSplit = $(this).attr('id').split('_'),
identName = $('#cont_' + thumbSplit[1]);

identName.toggle();
$('.content-window').not(identName).hide();
});
$('.close').on("click", function() {
$(this).parents('.content-window').hide();
closeButton.remove();
});
});

HERE是我的第一个建议的 fiddle ,这确实还不错。在您的单击函数中,我检查是否存在任何现有的 .close 类。如果有,我只是将其附加到您想要的区域,因此它及其单击事件仅创建一次:

$('.thumbnails li img').click(function() {
var thumbSplit = $(this).attr('id').split('_');
// descrSplit = $('.descriptions').find('.content-window').attr('id').split('_'),
identName = $('#cont_' + thumbSplit[1]);

identName.toggle();
$('.content-window').not(identName).hide();

var closeButton = $('.close');
if (closeButton.length == 0) {
closeButton = $('<button class="close">close</div>');
closeButton.click(function() {
$(this).parents('.content-window').hide();
closeButton.remove();
});
}
closeButton.appendTo(identName.not(':hidden'));
});

关于jquery - 如何防止按钮倍增?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19800362/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com