In many cases, we often use JavaScript to operate on the attributes of HTML elements, such as obtaining or setting the values of the input elements in the following HTML code block;
1 |
<Input Id = "input_btn" Type = "button" Value = "kanqd.com" /> |
We often write the following code:
1 2 |
VaR inputobj = Document. getelementbyid ('input _ BTN '); Alert (inputobj. value ); |
As we thought, kanqd.com is displayed on the page.
Problem:In some application scenarios, we need to add some custom attributes to the HTML element to meet the application requirements. For example, to add an info attribute to the preceding input tag, the Code is as follows:
1 |
<Input Id = "input_btn" Type = "button" Value = "kanqd.com" info = "this is a self defined attribute" />; |
If we still operate with the same code:
1 2 |
VaR inputobj = Document. getelementbyid ('input _ BTN '); Alert (inputobj.info ); |
After execution, you will find that "this is a self-defined attribute" is displayed in IE, but an error occurs in Firefox because IE automatically resolves the custom attribute to the Dom, there is no difference with standard attributes, but Firefox has a higher limit on the use of custom attributes.
The Compatibility method is as follows:
1. Use the element attributes [] set to access:
1 2 3 4 |
VaR inputobj = Document. getelementbyid ('input _ BTN '); Alert (inputobj. attributes ['info']. nodevalue ); Inputobj. attributes ['info']. nodevalue = 'This is a new info '; Alert (inputobj. attributes ['info']. nodevalue ); |
2. Use getattribute and setattribute to perform the following operations:
1 2 3 4 |
VaR inputobj = Document. getelementbyid ('input _ BTN '); Alert (inputobj. Getattribute ('info ')); Inputobj. setattribute ('info', 'This is a new info '); Alert (inputobj. Getattribute ('info ')); |
^ _ ^:
Note: The custom attributes mentioned here refer to the element attributes defined on the HTML page. The attributes dynamically created using JavaScript do not have this problem.