Javascript 为什么 if (element.innerHTML == "") 在 Firefox 中不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3676927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
why if (element.innerHTML == "") is not working in firefox
提问by Mahmoud Farahat
why is if (element.innerHTML == "")not working in firefox
为什么if (element.innerHTML == "")在 Firefox 中不起作用
but works fine in IE , any ideas please ?
但在 IE 中工作正常,有什么想法吗?
回答by user113716
Hard to say without seeing your HTML, but I'd say probably because you have some empty white space in the element, and IE doesn't treat that as a text node, while FF does.
很难说没有看到您的 HTML,但我会说可能是因为您在元素中有一些空白,并且 IE 不会将其视为文本节点,而 FF 会。
I believe it is actually a more strict standards compliance to treat any empty white space between tags as a text node, but IE doesn't comply.
我相信将标签之间的任何空白区域视为文本节点实际上是更严格的标准合规性,但 IE 不遵守。
You could do:
你可以这样做:
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 == '') {...
Or just get rid of the whitespace in your HTML markup manually.
或者只是手动删除 HTML 标记中的空格。
回答by naivists
You could check if element.innerHTML.trim() == ""for the best results. However, then you have to extend the string prototype with a trim()method:
您可以检查是否element.innerHTML.trim() == ""获得最佳结果。但是,您必须使用一种trim()方法扩展字符串原型:
if (!String.prototype.trim) {
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };
}
if (element.innerHTML.trim() == "") {
//do something
}
回答by palswim
An alternative method to check for the empty string is to check the length:
检查空字符串的另一种方法是检查长度:
element.innerHTML.length == 0
But, you'd still have to trim()if you had a whitespace string you wanted to match.
但是,trim()如果您有想要匹配的空白字符串,您仍然必须这样做。
回答by Third
For me, it seemed like setting my innerHTMLwas not working in Firefoxnor Chromebut it did work in IEbecause of my error. It turned out that I was never getting the element using getElementByIdin the first place. IEseems to do just fine with elements which are defined with name=with getElementByIdbut Firefoxand Chromewas more stringent and accepts only id=elements. (More correctly in my view)
I hope this saves somebody some frustration.
Why does IE do these sorts of things and confuse people...
对我来说,这似乎是我的设置innerHTML是不是在工作Firefox,也不Chrome但它没有工作IE,因为我的错误。事实证明,我从来没有使用过这个元素getElementById。IE似乎有被定义的元素做就好name=用getElementById,但Firefox和Chrome更严格,只接受id=元素。(在我看来更正确)我希望这可以避免某些人感到沮丧。
为什么 IE 会做这些事情并使人们感到困惑......

