JavaScript and Js scripts handle the custom attribute resolution of HTML elements which is compatible with Firefox and IE

  • 2020-03-29 23:57:13
  • OfStack

HTML elements, attributes are already very rich. However, custom attributes play a key role in situations where you may be stretched.

Custom attributes of Html elements, easy to use, such as:

< Input type= "button" value= "Click Me, Baby!" / >

So let's say we want to limit this button, this button, to two clicks, and then it's gone.

The usual way to do this is to use global variables to record the number of clicks, but we use custom properties to do this, to show the advantages of custom properties; Let's change the button above:

< Input type= "button" value= "Click Me, Baby!" ClickCount = "0" / >

As you can see, I added a custom property, clickCount, to the button and set the initial value to 0. Let's write the function of the js code:

1. Add click event handling to the button

< Input type= "button" value= "Click Me, Baby!" ClickCount = "0"   The onclick = "customAttributeDemo (this);" / >

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

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


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 a higher limit on the use of custom attributes and can only be accessed using the attributes[] collection. The code under FireFox:

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

The above code also applies to IE, so this code, is the code with compatibility.

Thanks to the netizens' communication, he gave the methods of getAttribute and setAttribute:


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


Related articles: