如何使用jQuery检查HTML元素是否为空? [英] How do I check if an HTML element is empty using jQuery?

查看:370
本文介绍了如何使用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.

这篇关于如何使用jQuery检查HTML元素是否为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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