jQuery确定标签是否为空 [英] jQuery determine if a tag is empty
本文介绍了jQuery确定标签是否为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我几乎已经明白了,但是只需要稍微推动一下即可.我正在解析一个包含(可能)HTML的字符串.这是代码:
I've almost got this but just need a little push over the edge. I'm parsing a string which contains (potentially) HTML. Here's the code:
function clean(snippet) {
OBJ = $(snippet);
txt = OBJ.text();
if(txt) {
parsed = txt;
} else {
parsed = snippet;
}
return parsed;
}
这是我的测试用例:
alert(clean("<div>Randomness</div>")); // Alerts "Randomness"
alert(clean("Randomness")); // Alerts "Randomness"
alert(clean("<div></div>")); // Alerts "<div></div>" - should be blank
我真的无法弄清楚如何确定它只是一个传入的空标记还是纯文本,以及如何处理它.因此,我需要进行测试以查看标签是否为空.不确定这是否是最好的方法.
I can't really figure out how to determine if its just an empty tag that gets passed in vs just plain text and how to deal with it. So I need a test to see if a tag is empty, perhaps. Not sure if that's the best way.
推荐答案
您可以测试查询是否返回任何对象:
You can test if your query returns any objects:
function clean(snippet) {
OBJ = $(snippet);
if(OBJ.length == 0)
return snippet;
txt = OBJ.text();
return txt;
}
这篇关于jQuery确定标签是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文