jQuery using 'this' in an if statement

浪子不回头ぞ 提交于 2019-12-03 16:59:09

问题


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();
}

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).

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


回答1:


Edit: Added DEMO Link

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();



回答2:


you could use each to iterate through elements

$('input').each(function(){
  if ($(this).val()) {
    $(this).addClass('has-value');
  }
});



回答3:


Simple solution is to place the element in a variable.

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


来源:https://stackoverflow.com/questions/10002256/jquery-using-this-in-an-if-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!