jQuery在if语句中使用'this' [英] jQuery using 'this' in an if statement

查看:940
本文介绍了jQuery在if语句中使用'this'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 if 语句来确定某个元素是否包含任何子元素。如果它没有任何孩子,我只想对该元素做一些事情。

I'm using an if statement in order to determine if an element has any children. If it does NOT have any children, I want to do something to that element only.

这是我正在尝试做的前提:

Here's the premise of what I'm trying to do:

if ($("#div a").children().length > 0){
    $(this).hide();
}

因此,如果< a> 标签没有子节点,我想对该特定元素(或多个也没有子节点的元素)做一些事情。

So if an <a> tag has no children, I want to do something to that specific element (or multiple elements that also have no children).

问题在于尚未定义,因为它是 if 语句。

The problem is that this hasn't been defined because it's an if statement.

我可能完全错过了一些东西,但我不太清楚如何实现这一目标。任何建议将不胜感激

I could be completely missing something but I'm not quite sure how to accomplish this. Any advice would be appreciated

推荐答案

编辑:已添加 DEMO 链接

Added DEMO Link

您可以使用 .filter 检查条件并在过滤结果上调用 .hide 。见下文,

You can use .filter to check the condition and call .hide on the filter results. See below,

$("#div a").filter(function () {
  return ($(this).children().length > 0)
}).hide();

这篇关于jQuery在if语句中使用'this'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆