Home >Web Front-end >JS Tutorial >jquery modify attribute value example code (set attribute value)_jquery

jquery modify attribute value example code (set attribute value)_jquery

WBOY
WBOYOriginal
2016-05-16 17:05:151637browse

Set attributes - attr()

The jQuery attr() method is also used to set/change attribute values.

The following example demonstrates how to change (set) the value of the href attribute in a link:

Example

Copy code The code is as follows:

$("button").click (function(){
$("#keleyi").attr("href","http://www.jb51.net");
});

The attr() method also allows you to set multiple attributes simultaneously.
The following example demonstrates how to set both the href and title attributes:


Example

Copy code The code is as follows:

$("button" ).click(function(){
$("#keleyi").attr({
"href" : "http://www.jb51.net",
"title" : "Keleyi Net"
});
});

Callback function of attr()

jQuery method attr() also provides callback function. The callback function takes two parameters: the index of the current element in the selected element list, and the original (old) value. Then return the string you wish to use as the function's new value.

The following example demonstrates the attr() method with a callback function:

Example

Copy code The code is as follows:

$("button").click (function(){
$("#keleyi").attr("href", function(i,origValue){
return origValue "/jquery";
});
}) ;
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn