Does it use custom attributes?

I want to cancel any links and add additional attributes to each. Below is an example of how I achieved this.

function anularEnlaces(){ $('nav a').each(function(){ var href = $(this).attr('href'); var id = $(this).attr('id'); $(this).attr('href','javascript:void(0)'); $(this).attr('hrefnot',href); $(this).attr('nivel','uno'); $(this).attr('seccion','dos'); }); } 

My question is, what is the valid / recommended way to add custom attributes?

+4
source share
3 answers

Not this way. If you are using HTML5 doctype, you can use the new data-* attributes and then use jQuery data :

 $(this).data("hrefnot", href); 

And HTML:

 <a href="somewhere.html" data-hrefnot="something">A link</a> 

If you don’t need to first store the data in your tags, then it doesn’t matter if you use the HTML5 type or not (the jQuery data method will work).

+7
source

Indeed, if you are using HTML5, you can add your own data- data data- :

HTML5 Custom Data Attributes (data- *)

and you can use jQuery $.data to read and modify them.

+3
source

No, you should use data () instead of user element attributes and attr () (or better yet prop () ) for standard html attributes.


Data usage example ():

 <a hred="some/url" data-custom="value">test</a> // getter var customValue = $('a').data('custom'); var customUndefined = $('a').data('testing'); 

CustomValue now contains the string "value" and customUndefined contains undefined

 // setter $('a').data('custom', 'test'); $('a').data('testing', true); 
+2
source

Source: https://habr.com/ru/post/1382469/


All Articles