【问题标题】:How to access the element using "this"如何使用“this”访问元素
【发布时间】:2010-08-25 22:35:32
【问题描述】:


我需要在每个 DIV 标记中访问 SPAN 标记
所以我使用了以下代码

    $("DIV").click(function(){      
    $(this + "SPAN").show();
});


上面的代码是否正确?它不适合我!它也没有显示任何内容..
请帮帮我


谢谢,
Praveen J

【问题讨论】:

    标签: jquery html jquery-selectors jquery-traversing


    【解决方案1】:

    您可以使用.find() 来获取另一个元素中的元素,如下所示:

    $("div").click(function(){      
      $(this).find("span").show();
    });
    

    作为一般规则,要获得与this 相关的任何内容,您通常会从$(this)tree traversal functions 的某种组合开始移动。


    对于实际代码,基于以下 cmets:
    如果您的代码如下所示:

    <fieldset>
      <legend>Link</legend>
      <span>CHECK</span>
    </fieldset> 
    

    然后.find() 将不起作用,因为$("legend") 选择器因为&lt;span&gt; 不在内部 &lt;legend&gt; 它是一个兄弟,所以使用.siblings()(可选与选择器)像这样:

    $("legend").click(function(){ 
      $(this).siblings("span").show(); 
    });​
    

    You can give it a try here

    【讨论】:

    • 使用this 作为“上下文”是一种替代方法:$("div").click(function(){ $("span", this).show(); });
    • @digitala - 它已转换为相同的 .find() 调用 :) 只需更多步骤即可到达那里,包括 2 个正则表达式 :) ....您可以在此处查看源代码:@ 987654326@
    • 源码是这样的!
      Link CHECK
      解决方案很好,但在这里不起作用..
    • @praveenjayapal - 我没有看到 &lt;div&gt; 在那里...你能发布所有相关的内容吗?
    • 这里是确切的代码,
      Link CHECK
      $("legend").click(function(){ $ (this).find("span").show(); });最初 span 是隐藏的
    【解决方案2】:

    您可以使用查找功能来做到这一点。 (另外,选择器最好使用小写。)

    $("div").click(function(){      
        $(this).find("span").show();
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-12
      • 1970-01-01
      • 2011-02-14
      • 2010-11-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多