Pitfalls caused by improper use of HTML () methods in jquery _jquery

Source: Internet
Author: User
View Source
Copy Code code as follows:

return this[0] && This[0].nodetype = = 1?
This[0].innerhtml.replace (Rinlinejquery, ""):
Null

Know that it passes through non-standard innerHTML implementations that are supported by all browsers.
Some consumers use the return value of the HTML () method as a 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 fine, but if there are spaces inside the HTML element of the Id=user, you won't get the results you want. Like what:
Copy Code code as follows:

<div id= "User" > Jack</div>
<script>
Alert (document.getElementById (' user '). innerhtml.length);
</script>

Div[id=user] inside the text jack before the more than careful 3 spaces, this time in the browser performance is not the same:
IE6/78, the length of the pop-up string is 4, that is, the space is ignored.
In Ie9/firefox/safari/chrome/opera, the pop-up is 7, that is, no spaces are ignored.
The condition that takes the return value of the. html () as a branch of code is clearly an error in non IE browsers.
The solution is simple if you want to use the HTML content of the element as a criterion
1, when writing HTML, remove space
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
Only innerHTML return values in IE6/7/8 ignore English spaces

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.