Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
131 views
in Technique[技术] by (71.8m points)

javascript - How to add an HTML attribute with jQuery

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...