如何使用jQuery检查HTML元素是否为空?

问题描述:

我正在尝试仅在HTML元素为空时使用jQuery调用函数。

I'm trying to call a function only if an HTML element is empty, using jQuery.

这样的事情:

if (isEmpty($('#element'))) {
    // do something
}


if ($('#element').is(':empty')){
  //do something
}

有关详细信息,请参阅 http://api.jquery.com/is/ http://api.jquery.com/empty-selector/

for more info see http://api.jquery.com/is/ and http://api.jquery.com/empty-selector/

编辑:

有些人指出,空元素的浏览器解释可能会有所不同。如果你想忽略不可见的元素,比如空格和换行符,并使实现更加一致,你可以创建一个函数(或者只使用它内部的代码)。

As some have pointed, the browser interpretation of an empty element can vary. If you would like to ignore invisible elements such as spaces and line breaks and make the implementation more consistent you can create a function (or just use the code inside of it).

  function isEmpty( el ){
      return !$.trim(el.html())
  }
  if (isEmpty($('#element'))) {
      // do something
  }

你也可以把它变成一个jQuery插件,但你明白了。

You can also make it into a jQuery plugin, but you get the idea.