jQuery使用元素的文本来切换包含相同文本的另一个元素?

我对jquery非常陌生,我一直在努力创造这个动作。 任何有关此事的帮助将不胜感激。

我需要在jquery中使用一种方法,允许用户单击一个范围并切换(即.toggle() )另一个包含与被点击的跨度相同的文本的div,而不必为每个单独的跨度重复相同的function。

我的例子:

  • art
    studio art ceramics
  • studio art
    Option 1 Option 2
    ceramics
    Option 1 Option 2
  • 如果用户要单击包含“studio art”的跨度,那么我希望包含“studio art”的div为“.toggle()”。 我知道我可以给我想要连接在一起的span和div提供一个独特的类,例如“.studio-art”,例如:

     $(document).ready(function(){ $("span.label.studio-art").click(function(){ $(".row-section.studio-art").toggle(); }); $("span.label.ceramics").click(function(){ $(".row-section.ceramics").toggle(); }); }); 

    Jsfiddle示例: http : //jsfiddle.net/KCRUSHER/6qLX7/

    但我想避免做我上面的事情,因为我可能有数百个跨度或类似的实例。

    所以基本上我希望能帮助创建一个解决方案,只需要一个span中的字符串来匹配我的“row-heading”div中的字符串。 因此,当单击跨度时,行节div将切换。

    感谢您提前提供的任何帮助。

    您可以使用jQuery的filter方法找到具有相同文本的所有其他div元素并切换它们。 你必须更明智地选择你的class级名称才能理解并且更容易理解。

     $(document).ready(function(){ $(".row-section span").click(function(){ var clickedText = $(this).text(); $(".row-section").filter(function(){ return $(this).find("div").text() === clickedText; }).toggle(); }); }); 

    更新小提琴: http : //jsfiddle.net/6qLX7/2/

    .filter文档: http : .filter

    我没有测试这个,但它应该工作。

     $(document).ready(function(){ $("span.label").click(function(){ var checkText = $(this).html(); $( ".row-section:contains('"+checkText+"')" ).each(function(index,element){ // This checks for exact match. If you want any "containing" match, remove the if-clause if($(element).html() == checkText) { $(element).toggle(); } }); }); }); 

    如果这有帮助,请告诉我。
    PS! 此函数区分大小写(有关详细信息,请参阅http://api.jquery.com/contains-selector/ 。)