为什么if(element.innerHTML =="")在firefox中不起作用

Mah*_*hat 16 html javascript firefox internet-explorer innerhtml

为什么if (element.innerHTML == "")不在firefox中工作

但在IE中工作正常,有什么想法吗?

use*_*716 18

很难说没有看到你的HTML,但我想说可能是因为你在元素中有一些空白空间,而IE并不把它当作文本节点,而FF却是这样.

我认为将标签之间的任何空白空间视为文本节点实际上是更严格的标准兼容性,但IE不符合.

你可以这样做:

var htmlstring = element.innerHTML;

  // use the native .trim() if it exists
  //   otherwise use a regular expression  
htmlstring = (htmlstring.trim) ? htmlstring.trim() : htmlstring.replace(/^\s+/,'');

if(htmlstring == '') {...
Run Code Online (Sandbox Code Playgroud)

或者只是手动删除HTML标记中的空白.

  • @Tomás - 你实际上可以摆脱你的正则表达式的后半部分.如果`innerHTML`只有空格,那么测试字符串的开头*和*结尾是多余的. (4认同)
  • var str = element.innerHTML(); str = str.replace(/ ^\s*|\s*$/g,""); if(str ==""){alert('我很聪明'); } (2认同)

pal*_*wim 7

检查空字符串的另一种方法是检查长度:

element.innerHTML.length == 0
Run Code Online (Sandbox Code Playgroud)

但是,trim()如果您有想要匹配的空白字符串,您仍然必须这样做。


nai*_*sts 5

You could check if element.innerHTML.trim() == "" for the best results. However, then you have to extend the string prototype with a trim() method:

if (!String.prototype.trim) {
    String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };
}

if (element.innerHTML.trim() == "") {
  //do something
}
Run Code Online (Sandbox Code Playgroud)