vit*_*tto 320 javascript jquery
我正在尝试仅在HTML元素为空时使用jQuery调用函数.
像这样的东西:
if (isEmpty($('#element'))) {
// do something
}
Run Code Online (Sandbox Code Playgroud)
Emi*_*mil 537
if ($('#element').is(':empty')){
//do something
}
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅http://api.jquery.com/is/和http://api.jquery.com/empty-selector/
编辑:
正如一些人所指出的那样,浏览器对空元素的解释可能会有所不同.如果您想忽略空格和换行符等不可见元素并使实现更加一致,您可以创建一个函数(或者只使用它内部的代码).
function isEmpty( el ){
return !$.trim(el.html())
}
if (isEmpty($('#element'))) {
// do something
}
Run Code Online (Sandbox Code Playgroud)
你也可以把它变成一个jQuery插件,但你明白了.
Ser*_*ltz 115
我发现这是唯一可靠的方法(因为Chrome和FF将空格和换行符视为元素):
if($.trim($("selector").html())=='')
Run Code Online (Sandbox Code Playgroud)
DMT*_*ner 60
使用空白选择器时,空格和换行符是主要问题.小心,在CSS中:empty伪类的行为方式相同.我喜欢这种方法:
if ($someElement.children().length == 0){
someAction();
}
Run Code Online (Sandbox Code Playgroud)
小智 26
!elt.hasChildNodes()
Run Code Online (Sandbox Code Playgroud)
是的,我知道,这不是jQuery,所以你可以使用这个:
!$(elt)[0].hasChildNodes()
Run Code Online (Sandbox Code Playgroud)
现在开心?
Ali*_*guy 19
jQuery.fn.doSomething = function() {
//return something with 'this'
};
$('selector:empty').doSomething();
Run Code Online (Sandbox Code Playgroud)
Dig*_*ane 12
如果是"空",则表示没有HTML内容,
if($('#element').html() == "") {
//call function
}
Run Code Online (Sandbox Code Playgroud)
空如在包含没有文字?
if (!$('#element').text().length) {
...
}
Run Code Online (Sandbox Code Playgroud)
在简历中,有很多选项可以确定元素是否为空:
1-使用html:
if (!$.trim($('p#element').html())) {
// paragraph with id="element" is empty, your code goes here
}
Run Code Online (Sandbox Code Playgroud)
2-使用text:
if (!$.trim($('p#element').text())) {
// paragraph with id="element" is empty, your code goes here
}
Run Code Online (Sandbox Code Playgroud)
3-使用is(':empty'):
if ($('p#element').is(':empty')) {
// paragraph with id="element" is empty, your code goes here
}
Run Code Online (Sandbox Code Playgroud)
4-使用 length
if (!$('p#element').length){
// paragraph with id="element" is empty, your code goes here
}
Run Code Online (Sandbox Code Playgroud)
另外,如果你试图找出输入元素是否为空,你可以使用val:
if (!$.trim($('input#element').val())) {
// input with id="element" is empty, your code goes here
}
Run Code Online (Sandbox Code Playgroud)