Home  >  Article  >  Web Front-end  >  Traps caused by improper use of html() method in JQuery_jquery

Traps caused by improper use of html() method in JQuery_jquery

WBOY
WBOYOriginal
2016-05-16 18:08:191177browse

View source code

Copy code The code is as follows:

return this[0] && this[0] .nodeType === 1 ?
this[0].innerHTML.replace(rinlinejQuery, "") :
null;

Known to pass non-standard but all browsers Both innerHTML implementations are supported.
Some users will use the return value of the html() method as the condition for code branching, such as:
Copy code Code As follows:

var str = $('#user').html();
if( str=='jack' ){
...
}else if( str=='tom' ){
...
}else if( str=='lily' ){
...
}

In most cases this is no problem, but if there are spaces within the html element with id=user, you will not get the desired result. For example:
Copy code The code is as follows:

jack

<script> <br>alert(document.getElementById('user').innerHTML.length); <br></script>

div[ id=user] accidentally added 3 spaces before the text jack. At this time, the behavior is different in each browser:
In IE6/78, the length of the pop-up string is 4, that is, the spaces are ignored.
In IE9/Firefox/Safari/Chrome/Opera, the pop-up value is 7, which means spaces are not ignored.
At this time, using the return value of .html() as the condition for code branching will obviously cause an error in non-IE browsers.
If you have to use the html content of the element as the judgment condition, the solution is very simple
1. Remove the spaces when writing html
2. Call the html() method and then call trim, such as var str = $( '#user').html().trim();

Related:

http://www.w3.org/TR/2008/WD-html5-20080610/dom.html#innerhtml0
InnerHTML return value only in IE6/7/8 The problem of ignoring English spaces

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn