Home  >  Article  >  Web Front-end  >  jquery attribute and custom attribute operations: attr() and removeAttr()

jquery attribute and custom attribute operations: attr() and removeAttr()

无忌哥哥
无忌哥哥Original
2018-06-29 11:46:002347browse

jquery attribute and custom attribute operations: attr() and removeAttr()

Preliminary knowledge: reader, setter

1. There are some functions that can be used according to the number of parameters. Different, perform different functions and return different values, similar to function overloading

2. Pass in a parameter, perform the read operation getter, and return the current value of the parameter, called: reader/get Setter

3. Pass in two parameters, perform the assignment operation setter, and modify the value of the current parameter, called: setter/modifier

4. This type of operation is determined based on the number of parameters. There are many type methods in jQuery, everyone should pay attention to */

1. attr(): Obtaining and setting element attributes

Must pass parameters

var res = $('img').attr()

single The parameters are to get: the value of the current attribute

var res = $('#pic').attr('src')

The double parameters are to get, the first is the attribute name, the second is the new value to be set

$('#pic').attr('src', '../images/gyy.jpg') 
$('#pic').attr('style', 'border-radius: 50%;box-shadow:2px 2px 2px #888')

It can be seen that attr() It is a typical two-in-one method that combines readers and setters.

attr() can obtain the custom attributes of elements.

html5, you can add users to tags through the data- prefix. The attribute value of the custom attribute

var res = $('#pic').attr('data-nation')

attr() also supports the callback function

$('#pic').attr('width', function(){return 100+50})

Note: The numerical type returned by the callback will be automatically converted to the character type and then assigned to the width attribute

var res = $('#pic').attr('width')

2. removeAttr(): Delete the attribute of the element

Delete the inline style attribute of the image

$('#pic').removeAttr('style')

You can delete multiple attributes, separated by spaces. Return the status of the current element

var res = $('#pic').removeAttr('alt title data-nation')

View the running results on the console

console.log(res)

The above is the detailed content of jquery attribute and custom attribute operations: attr() and removeAttr(). For more information, please follow other related articles on the PHP Chinese website!

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