使用jQuery+Javascript识别一个空文本节点

Identifying an empty text node with jQuery + Javascript

本文关键字:一个 文本 节点 jQuery+Javascript 识别 使用      更新时间:2023-09-26

你可能认为这很容易,但我正经历着最艰难的时刻。

以下是我试图识别的内容:

<span class="cw-value-one"></span>

以下是我目前使用的:

    $('span.cw-value-one').each(function(){
        var textNode = $(this).text();
        var type = typeof textNode;
        var len = textNode.length;
        if($(this).is(':empty')){
            $(this).siblings('span.cw-value-two').css({"position": "relative", "left": "1em"});
        }
    });

好的,那么textNode = ""type = stringlen = 1——它们都没有帮助识别空文本节点,因为a的类型是字符串,长度是1。jQuery .is(':empty')也不工作。

那么,在JQuery或纯ol'Javascript中,你是如何识别空文本节点的呢?

您可能在span中有空格,请使用trim()删除span中文本周围的空格(如果有的话)。

实时演示

  var textNode = $(this).text().trim();

尝试按文本长度进行检查。

$('span.cw-value-one').each(function(){
        var textNode = $(this).text();
        var type = typeof textNode;
        var len = textNode.length;
        if(len <= 0){
            $(this).siblings('span.cw-value-two').css({"position": "relative", "left": "1em"});
        }
    });​

我还建议对文本进行修剪。如果你想修剪文本,也一定要看到这篇关于不喜欢修剪的文章。JavaScript中的trim()在IE 中不起作用