问题
I am already using id and title but i need to parse through 2 more bits...
$(this).attr("title"); $(this).attr("id");
Will $(this).attr("custom1");
work ??
回答1:
yes, and BTW you can set multiple attributes at once:
$('.myselector').attr({
src: 'thefile.gif',
width: 200,
height: 300 });
回答2:
Yes, and you can use it for all of the data-attributes
in HTML5. Which is the preferrable way to add extra attributes.
Additionally, all data-*
attributes are automatically added to jQuery's data() object for easy access
回答3:
If you just want to associate (by name) some data with a DOM element, you're better off using the ".data()" method:
$(this).data('custom1', someValue);
The ".data()" API makes HTML5-style "data-foo" attributes coded into the HTML accessible:
var foo = $(this).data('foo'); // gets the "data-foo" attribute value from element
回答4:
Yes it works, but it's not a good idea.
Better use .data('foo', 'bar'); if you want to store some data on an element.
回答5:
Yes, and the best thing you can do is just test it.
<script>
$(document).ready(function() {
// Handler for .ready() called.
alert( "custom1 = " + $("#myField").attr("custom1") );
});
</script>
<div id="myField" custom1="My Custom Field"></div>
Now, you are breaking markup, so I would suggest storing your info in ALT tags or NAME tags to prevent that ().
来源:https://stackoverflow.com/questions/5223414/does-jquery-attr-allow-for-non-standards