Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Well, I have this jQuery image slideshow that uses the attribute "control" inside an <a>. Seeing how it didn't validate I searched for a way to add this attribute inside my HMTL via jQuery but I didn't really find anything relevant. Now I don't really care about how valid my page is, but I'm really curious in how to add an HTML attribute inside an HTML tag.

In case I wasn't clear enough with my explanation, I have this code:

<a id="previous" control="-6" href="#"></a>

And I want to add control="-6" with jQuery.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
118 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use jQuery's attr function

$("#previous").attr("control", "-6");

An example

// Try to retrieve the control attribute
// returns undefined because the attribute doesn't exists
$("#previous").attr("control");

// Set the control attribute
$("#previous").attr("control", "-6");

// Retrieve the control attribute (-6)
$("#previous").attr("control");

See this example on jsFiddle


You can alternatively use data function to store values on elements. Works the same way, for example:

$("#previous").data("control"); // undefined
$("#previous").data("control", "-6"); // set the element data
$("#previous").data("control"); // retrieve -6

Using data you can store more complex values like objects

$("#previos").data("control", { value: -6 });
($("#previos").data("control")).value; // -6

See a data example on jsFiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...