Home  >  Article  >  Web Front-end  >  JavaScript/Js script handles custom attribute parsing of html elements (personal test compatible with Firefox and IE)_javascript skills

JavaScript/Js script handles custom attribute parsing of html elements (personal test compatible with Firefox and IE)_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:12:32753browse

HTML elements have very rich attributes. However, in some cases, it may be too tight. At this time, custom attributes play a very critical role.

Custom attributes of Html elements are very convenient to use, for example:

Suppose we need to limit it now. This button can only be clicked 2 times, and then it will become invalid.

The usual implementation method is to use global variables to record the number of clicks, but here we use custom attributes to implement this function and show the advantages of custom attributes; let’s modify the button above:

As you can see, I added a custom attribute clickCount to this button and set the initial value to 0; let’s write the js code to implement the function:

1. Add click event processing to button

2. Let’s write the function customAttributeDemo(obj)

For IE, using custom attributes is very simple, because IE automatically parses custom attributes into the DOM, which is no different from standard attributes. The version under IE:

Copy code The code is as follows:

function customAttributeDemo(obj)
{
if (obj.clickCount === '0' )
{
obj.clickCount = '1';
}
else
{
obj.disabled = true;
}
}

The above code will be invalid under FireFox because FireFox has higher restrictions on the use of custom attributes and can only be accessed using the attributes[] collection. The code under FireFox:
Copy code The code is as follows:

function customAttributeDemo(obj)
{
if (obj.attributes['clickCount' ].nodeValue === '0')
{
obj.attributes['clickCount'].nodeValue = '1';
}
else
{
obj.disabled = true;
}
}

The above code is also applicable to IE, so this code is compatible code.

Thanks to the netizen for the exchange, he gave the methods of getAttribute and setAttribute:

Copy the code The code is as follows:

function customAttributeDemo(obj)
{
if (obj.getAttribute('clickCount') === '0')
obj.setAttribute('clickCount', '1') ;
else
obj.disabled = true;
}
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