Traps caused by improper use of the HTML () method in jquery

Source: Internet
Author: User

View Source Code CopyCode The Code is as follows: return this [0] & this [0]. nodetype = 1?
This [0]. innerhtml. Replace (rinlinejquery ,""):
NULL;

It is known that it is implemented through non-standard innerhtml that all browsers support.
Some users use the return value of the HTML () method as the condition for code branch, such:Copy codeThe Code is 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 the HTML element of ID = user contains spaces, the desired result will not be obtained. For example:Copy codeThe Code is as follows: <Div id = "user"> Jack </div>
<SCRIPT>
Alert (document. getelementbyid ('user'). innerhtml. Length );
</SCRIPT>

In Div [ID = user], three spaces are accidentally added before the text Jack. At this time, the performance of each browser is different:
In IE6/78, the length of the pop-up string is 4, that is, spaces are ignored.
In ie9/Firefox/Safari/Chrome/Opera, the pop-up is 7, that is, no space is ignored.
In this case, when the return value of .html () is used as the condition for code branches, it is obvious that errors will occur in non-ie browsers.
If you have to use the HTML content of the element as the judgment condition, the solution is simple.
1. Remove spaces when writing HTML.
2. Call the HTML () method and then trim, for example, var str = require ('{user'}.html (). Trim ();

Related:

Http://www.w3.org/TR/2008/WD-html5-20080610/dom.html#innerhtml0
Only the innerhtml returned values in IE6/7/8 ignore English spaces.

Related Article

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.