我正在尝试制作一个有效的开关,但我点击的每个元素都会创建这些显示元素的堆栈。相反,我试图隐藏所有内容并仅显示我单击的元素。现在我只能在我点击同一个元素两次时隐藏它,这不是我想要的。我想单击一个并隐藏之前显示的那些。
.totalpoll-choice-image-2
是一堆必须始终显示的图像。它们是用户单击以在每个图像下显示隐藏描述的内容。当我点击 .totalpoll-choice-image-2
时,该描述就会出现。该类别有 5 张图片。我点击的下一张图片,我想隐藏之前的描述框。
我的代码:
jQuery(document).ready(function() {
var element = document.getElementsByClassName("totalpoll-choice-image-2");
var elements = Array.prototype.slice.call(Array.from( element ) );
console.log(elements);
jQuery(element).each(function(item) {
jQuery(this).unbind('click').click(function(e) {
e.stopPropagation();
var id = jQuery(this).attr("data-id");
console.log(this);
//jQuery("#" + id).css({"display": 'block !important'});
//document.getElementById(id).style.setProperty( 'display', 'block', 'important' );
var descriptionContainer = document.getElementById(id);
var thiss = jQuery(this);
console.log(thiss);
console.log(jQuery(descriptionContainer).not(thiss).hide());
jQuery(descriptionContainer).toggleClass("show");
});
})
})
最佳答案
您可以使用 jQuery 一次将事件处理程序附加到一组 DOM 元素。因此,在这种情况下,混合 vanilla JS 和 jQuery 对你没有任何好处——尽管这是可能的。
我把这个小例子放在一起,说明您想要做什么。 脚本本身非常简单(如下所示)。类和ID不同,但思路应该是一样的:
// Assign click handlers to all items at once
$('.img').click(function(e){
// Turn off all the texts
$('.stuff').hide();
// Show the one you want
$('#' + $(e.target).data('id')).show();
})
https://codepen.io/meltingchocolate/pen/NyzKMp
您可能还注意到我使用 .data() method 从 data-id 属性中提取了 ID , 并将事件监听器附加到 .click() method .这是跨一组 jQuery 对象应用事件处理程序的典型方法。
关于javascript - 单击另一个元素时无法隐藏其他元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48915689/