如何使用“this”访问元素

发布于 2024-09-15 14:05:44 字数 227 浏览 0 评论 0原文


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

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


上面的代码是否正确?它对我不起作用!它也没有显示任何内容..
请帮助我


谢谢,
Praveen J

I need to access a SPAN tag with in every DIV tag
so i used this following code

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

Is the above code is correct? Its not working for me! Its showing nothing too..

Please help me

Thanks,
Praveen J

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

书信已泛黄 2024-09-22 14:05:44

您可以使用 .find() 来获取另一个元素中的元素,像这样:

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

作为一般规则,要获取与 this 相关的任何内容,您通常会从 $(this)树遍历函数 进行移动。


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

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

那么 .find() 不会'从 $("legend") 选择器开始工作,因为 不在

内部

它是同级,所以使用 .siblings() (可选地使用选择器)如下所示:

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

您可以在这里尝试一下

You can use .find() for getting an element inside another, like this:

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

As a general rule, to get anything relative to this, you're typically going to start with $(this) and some combination of the tree traversal functions to move around.


For actual code, based on comments below:
If your code looks like this:

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

Then .find() won't work since on $("legend") selector because the <span> isn't inside the <legend> it's a sibling, so use .siblings() (optionally with a selector) like this:

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

You can give it a try here

原来是傀儡 2024-09-22 14:05:44

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

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

You can use the find function to do that. (Also, using lowercase for selectors is preferred.)

$("div").click(function(){      
    $(this).find("span").show();
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文