Home  >  Article  >  Web Front-end  >  Operations on inherent attributes of jquery elements: prop() and removeProp()

Operations on inherent attributes of jquery elements: prop() and removeProp()

无忌哥哥
无忌哥哥Original
2018-06-29 11:49:381745browse

Operations of the inherent attributes of jquery elements: prop() and removeProp()

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>2.元素固有属性的操作:prop()和removeProp()</title>
</head>
<body>
<img src="../images/fbb.jpg" width="200" alt="美女" title="明星" id="pic" data-nation="中国">
</body>

1.prop(): Only the inherent attributes of the element can be obtained

Get the inherent attributes alt, title

var res = $(&#39;#pic&#39;).prop(&#39;alt&#39;)
var res = $(&#39;#pic&#39;).prop(&#39;title&#39;)

Get the custom attribute data-nation, return undefined, and cannot get it

var res = $(&#39;#pic&#39;).prop(&#39;data-nation&#39;)

But how to use prop() to dynamically set the custom attribute, you can get it normally

var res = $(&#39;#pic&#39;).prop(&#39;data-nation&#39;,&#39;中国山东&#39;)

Looking at the element at this time, it is found that the custom attribute has not changed, so this setting has no impact on the element.

The custom attribute value viewed again at this time is only a temporary value that exists in the current script. Data

var res = $(&#39;#pic&#39;).prop(&#39;data-nation&#39;)

2.removeProp()

This method is different from removeAttr() in two points:

1. It does not support space-separated attribute list strings, that is, once Only one attribute can be deleted

2. It cannot delete native attributes. If you really want to delete it, just set the value to false

You cannot remove multiple attributes at the same time, so this statement Invalid

var res = $(&#39;#pic&#39;).removeProp(&#39;alt data-nation&#39;)

Delete the custom attribute data-nation

var res = $(&#39;#pic&#39;).removeProp(&#39;data-nation&#39;)

Delete the native attribute alt, the deletion failed

var res = $(&#39;#pic&#39;).removeProp(&#39;alt&#39;)

Use removeAttr() to delete the native attribute alt, the deletion was successful

var res = $(&#39;#pic&#39;).removeAttr(&#39;alt&#39;)

So, if you want to use removeProp() to delete native properties, in most cases you can set the value to false

Ultimately, it will be processed by the user script

var res = $(&#39;#pic&#39;).prop(&#39;alt&#39;,false)
var res = $(&#39;#pic&#39;).prop(&#39;alt&#39;)

Console query Result

console.log(res)

The above is the detailed content of Operations on inherent attributes of jquery elements: prop() and removeProp(). 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