如何在一个选择器jQuery中显示和隐藏多个元素?
当我单击带有类hidden_element
元素时,我想显示ID为hidden_element
的隐藏元素,当我点击ID为hidden_element
的元素时,关闭ID为hidden_element
元素,如果我只是制作一个我的脚本可以正常工作,但我有三个元素有相同的CLASS和ID,它不能工作,有人请帮助。
这是我的剧本
我的jQuery脚本是
$(this).find(".show_hidden_element").click( function(){ $(this).find("#hidden_element").show(); }); $(this).find("#close_hidden_element").click( function(){ $(this).find("#hidden_element").hide(); });
id
和class
之间的区别在于id
是唯一的,class不是。 元素也可以有多个类,但唯一的id。
使用class="close_hidden_element button_close"
。
Lorem Ipsum
× Lorem Ipsum
× Lorem Ipsum
×
而你的jquery应该是。
$(document).on('click', 'div.show_hidden_element',function(){ $(".hidden_element").show(); }); $(document).on('click', 'div.close_hidden_element',function(){ $(".hidden_element").hide(); });
建议 :请阅读http://css-tricks.com/the-difference-between-id-and-class/
页面上的元素必须具有唯一 ID。 如果您希望这个工作,您需要将它们更改为类。 您是否希望每个
仅通过各自的触发器隐藏/显示?
Lorem Ipsum
× Lorem Ipsum
× Lorem Ipsum
×
jQuery的
$("article").on("click",".show_hidden_element",function(){ $(this).find(".hidden_element").show(); }); $("article").on("click",".close_hidden_element",function(){ $(this).closest(".hidden_element").hide(); });
实际上,由于show_hidden_element
类的放置,这不能正常工作。 您可能最好将×
作为切换,如下所示:
Lorem Ipsum
× $(function () { $("article").on("click", ".close_hidden_element", function () { $(".hidden_element").toggle(); }); });
您不能为多个元素使用相同的ID。 您必须将id转换为所有id =“hidden_element”(以及其他人)的类,然后使用类似的东西。
Lorem Ipsum
Lorem Ipsum
Lorem Ipsum
jQuery的
$(".show_hidden_element").click( function(){ $(this).find(".hidden_element").show(); }); $(".button_close").click( function(){ $(this).closest(".hidden_element").hide(); });