作为层次结构 jQuery 的条件语句

发布于 2024-08-27 07:00:14 字数 336 浏览 3 评论 0原文

有没有办法让 jQuery 使用条件语句中的对象作为层次结构中的对象。例如,我想验证某些内容是否存在,然后告诉它仅使用 this 选择器执行某些操作。

像这样

if ($(".tnImg").length) {

//我必须声明我在这里定位的对象才能使其工作

            $(this).animate({
            opacity: 0.5,   
            }, 200 );
  }

有没有办法让 jQuery 做到这一点? 我想没有太大的好处,但我仍然很好奇

Is there a way to make jQuery use objects in a conditional statement as an object in a hierarchy. For Example, I want to validate that something exist then tell it to do something just using the this selector.

Like this

if ($(".tnImg").length) {

//i have to declare what object I am targeting here to get this to work

            $(this).animate({
            opacity: 0.5,   
            }, 200 );
  }

Is there a way to get jQuery to do this?
I guess theres not a huge benefit but i still am curious

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

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

发布评论

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

评论(1

以歌曲疗慰 2024-09-03 07:00:14

在 jQuery 中,如果没有找到任何内容,那么什么也不会发生,例如:

$(".tnImg").animate({ opacity: 0.5 }, 200 );

这不会出错,如果它没有找到 class="tnImg" 的任何内容,它就不会在任何元素上运行。这是使 jQuery 如此简洁的基本原理之一:)

如果您想对对象做很多事情,这将允许您将它用作每个对象的 $(this)

$(".tnImg").each(function() {
  //$(this) is the current class="tnImg" element, this code runs for each one
  $(this).animate({ opacity: 0.5 }, 200 );
});

In jQuery, if nothing is found, then nothing happens, for example:

$(".tnImg").animate({ opacity: 0.5 }, 200 );

This won't error, if it doesn't find anything with class="tnImg" it simply won't run on any elements. This is one of the fundamentals that makes jQuery so terse :)

If you wanted to do lots with the object, this would let you use it as $(this) for each one:

$(".tnImg").each(function() {
  //$(this) is the current class="tnImg" element, this code runs for each one
  $(this).animate({ opacity: 0.5 }, 200 );
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文