


Detailed explanation of usage examples of attr() and prop() functions in jQuery (with usage differences)_jquery
この記事の例では、jQuery での attr() 関数と prop() 関数の使用法について説明します。参考のために皆さんと共有してください。詳細は次のとおりです:
1. jQuery の attr() メソッド
attr() メソッドは jQuery で要素の属性を取得および設定するために使用されます。attr は Attr() の略称で、jQuery の DOM 操作でよく使用されます。
1. attr (属性名) //属性の値を取得 (最初に一致した要素の属性値を取得します。このメソッドは、最初に一致した要素から属性の値を簡単に取得できます。対応する属性がある場合は、未定義を返します)
2. attr(属性名, 属性値) //属性の値を設定します (一致するすべての要素に属性値を設定します)
3. attr (属性名, 関数値) //属性の関数値を設定します (一致するすべての要素に対して計算された属性値を設定します。値を指定するのではなく、関数を指定し、これによって計算される値を指定します)関数は属性値です。)
4.attr(properties) //指定された要素に複数の属性値を設定します。つまり、{属性名 1: "属性値 1"、属性名 2: "属性値 2"、… … }。 (これは、一致するすべての要素にわたって多くの属性をバッチで設定する最良の方法です。オブジェクトのクラス属性を設定したい場合は、属性名として「className」を使用する必要があることに注意してください。または、「class」を直接使用することもできます。または「ID」)
サンプルコード:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>jquery中attr()方法</title> <script src="js/jquery-1.4.2.min.js" language="javascript" type="text/javascript" ></script> <style> p{color:red} li{color:blue;} .lili{font-weight:bold;color:red;} #lili{font-weight:bold;color:red;} </style> </head> <body> <p title="你最喜欢的水果是。">你最喜欢的水果是?</p> <ul> <li title="苹果汁">苹果</li> <li title="橘子汁" alt="123">橘子</li> <li title="菠萝汁">菠萝</li> </ul> <script> ... </script> </body> <html>
1.attr(name)//属性の値を取得します
1.1 attr(name) を使用してタイトル値を取得します:
<script> alert($("ul li:eq(1)").attr("title")); </script>
結果:
1.2 attr(name) を使用して alt 値を取得します:
<script> alert($("ul li:eq(1)").attr("alt")); </script>
結果:
2. attr(name,value) //属性の値を設定します
2.1 attr(name,value) を使用してタイトルの値を次のように変更します: オレンジは食べないでください
<script> $("ul li:eq(1)").attr("title","不吃橘子"); alert($("ul li:eq(1)").attr("title")); </script>
結果:
3. attr(name,fn) //属性の関数値を設定します
3.1 alt 属性の値を title 属性の値に設定します。
<script> $("ul li:eq(1)").attr("title",function(){ return this.alt}); alert($("ul li:eq(1)").attr("title")); </script>
結果:
4.attr(properties) //「名前/値」の形式でオブジェクトを、一致するすべての要素の属性として設定します
4.1
- の 2 番目の
- を取得し、title 属性と alt 属性を設定します。
<script> $("ul li:eq(1)").attr({title:"不喝橘子汁",alt:"不是123"}); alert($("ul li:eq(1)").attr("title")); alert($("ul li:eq(1)").attr("alt")); </script>
結果:
4.2
- の 2 番目の
- 設定クラスを取得します。
<script> $("ul li:eq(1)").attr({className:"lili"}); </script>
結果:
4.3
- の 2 番目の
- の設定 ID を取得します。
<script> $("ul li:eq(1)").attr({id:"lili"}); </script>
結果:
4.4
- の 2 番目の
- を取得し、スタイルを設定します。
<script> $("ul li:eq(1)").attr({style:"color:red"}); </script>
結果:
li に alt を追加するのは間違いです。img、area、input 要素 (アプレット要素を含む) でのみ使用できます。 input 要素の場合、alt 属性は送信ボタンの画像を置き換えることを目的としています。ここでは attr() メソッドを詳しく説明するために適切な属性がないため、attr() メソッドの使用方法の学習と参照のみを目的として alt を使用します。
alt と tite の違いは次のとおりです。
alt: 画像を説明するために使用されるテキストです。画像が表示できない場合、画像の代わりにこれらのテキストが表示されます。画像上にマウスを移動するとテキストも表示されます。
title: マウスを置いた後に表示されるテキストです。では、属性を削除するにはどうすればよいでしょうか?
jquery で属性を削除するキーワードは、removeAttr です。使用方法を参照してください。
使用法 1 と同じ HTML コードですが、li の title 属性を削除したいので、次のようにします。<script> $("ul li:eq(1)").removeAttr ("title"); </script>
これは非常に簡単です。attr は実際にはネイティブ JS での getAttribute の簡略化された実装であり、removeAttr は RemoveAttribute の略語です。
それでは、attr() に似た属性はあるのでしょうか?
jquery のval() は 、
と同等の要素ノードの値を設定します。
に似ています。 $(this).val(); $(this).attr("value");
と同等の要素ノードの値を取得します。 $(this).val(value); $(this).attr("value",value);2. jQuery の prop() メソッド:
prop() 関数は、現在の jQuery オブジェクトと一致する要素の属性値を設定または返すために使用されます。
この関数はjQueryオブジェクト(インスタンス)に属します。 DOM 要素のプロパティを削除する必要がある場合は、removeProp() 関数を使用します。
文法
この関数はjQuery 1.6で追加されました。 prop() 関数には次の 2 つの用途があります:
使用法 1:
jQueryObject.prop( propertyName [, value ] )
指定されたプロパティ propertyName の値を設定または返します。 value パラメーターが指定されている場合は、プロパティ propertyName の値を value に設定することを意味し、value パラメーターが指定されていない場合は、プロパティ propertyName の値を返すことを意味します。パラメータ値は関数にすることもできます。prop() は、一致したすべての要素に基づいて関数を実行します。関数内の this ポインターは、対応する DOM 要素を指します。 prop() は 2 つのパラメーターも関数に渡します。最初のパラメーターは一致する要素内の要素のインデックスで、2 番目のパラメーターは要素の propertyName 属性の現在の値です。関数の戻り値は、要素の propertyName 属性に設定された値です。
使用法 2:
jQueryObject.prop( オブジェクト )
任意の数のプロパティの値をオブジェクトとして同時に設定します。オブジェクト object の各属性は propertyName に対応し、属性の値は value に対応します。注: prop() 関数のすべての「属性の設定」操作は、現在の jQuery オブジェクトと一致する各要素に対して行われます。すべての「属性の読み取り」操作は、最初に一致した要素に対してのみ行われます。
パラメータ前の構文セクションで定義されたパラメーター名に基づいて、対応するパラメーターを見つけてください。
Parameters Description propertyName String type specifies the attribute name. value Optional/Object/Function type specifies the attribute value, or the function that returns the attribute value. object Object specified by type , used to encapsulate multiple key-value pairs and set multiple attributes at the same time. 返回值
prop()函数的返回值是任意类型,返回值的类型取决于当前prop()函数执行的是"设置属性"操作还是"读取属性"操作。
如果prop()函数执行的是"设置属性"操作,则返回当前jQuery对象本身;如果是"读取属性"操作,则返回读取到的属性值。
如果当前jQuery对象匹配多个元素,返回属性值时,prop()函数只以其中第一个匹配的元素为准。如果该元素没有指定的属性,则返回undefined。
prop()和attr()的主要区别:prop()函数针对的是DOM元素(JS Element对象)的属性,attr()函数针对的是DOM元素所对应的文档节点的属性。详情请查看jQuery函数attr()和prop()的区别。
注意事项
1、如果通过prop()函数更改和
2、如果使用prop()函数操作表单元素的checked、selected、disabled等属性,如果该元素被选中(或禁用),则返回true,否则(意即HTML中没有该属性)返回false。
3、prop()函数还可以设置或返回DOM元素的Element对象上的某些属性,例如:tagName、selectedIndex、nodeName、nodeType、ownerDocument、defaultChecked和defaultSelected等属性。
4、在IE9及更早版本中,如果使用prop()函数设置的属性值不是一个简单的原始值(String、Number、Boolean),并且在对应的DOM元素被销毁之前,该属性没有被移除,则可能会导致内存泄漏问题。如果你只是为了存储数据,建议你使用data()函数,以避免内存泄漏问题。
示例&说明
以下面这段HTML代码为例:
<div id="n1"> <p id="n2" class="demo test" data-key="UUID" data_value="1235456465">CodePlayer</p> <input id="n3" name="order_id" type="checkbox" value="1"> <input id="n4" name="order_id" type="checkbox" checked="checked" value="2"> </div>
我们编写如下jQuery代码:
var $n2 = $("#n2"); // prop()操作针对的是元素(Element对象)的属性,而不是元素节点(HTML文档)的属性 document.writeln( $n2.prop("data-key") ); // undefined document.writeln( $n2.prop("data_value") ); // undefined document.writeln( $n2.prop("id") ); // n2 document.writeln( $n2.prop("tagName") ); // P document.writeln( $n2.prop("className") ); // demo test document.writeln( $n2.prop("innerHTML") ); // CodePlayer document.writeln( typeof $n2.prop("getAttribute") ); // function // prop()设置的属性也是针对元素(Element对象),因此也可以通过元素本身直接访问 $n2.prop("prop_a", "CodePlayer"); document.writeln( $n2[0].prop_a ); // CodePlayer var n2 = document.getElementById("n2"); document.writeln( n2.prop_a ); // CodePlayer // 以对象形式同时设置多个属性,属性值可以是对象、数组等任意类型 $n2.prop( { prop_b: "baike", prop_c: 18, site: { name: "CodePlayer", url: "http://www.jb51.net/" } } ); document.writeln( $n2[0].prop_c ); // 18 document.writeln( $n2[0].site.url ); // http://www.jb51.net/ // 反选所有的复选框(没选中的改为选中,选中的改为取消选中) $("input:checkbox").prop("checked", function(index, oldValue){ return !oldValue; });
附:jquery中attr和prop的区别
在高版本的jquery引入prop方法后,什么时候该用prop?什么时候用attr?它们两个之间有什么区别?这些问题就出现了。
关于它们两个的区别,网上的答案很多。这里谈谈我的心得,我的心得很简单:
对于HTML元素本身就带有的固有属性,在处理时,使用prop方法。
对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法。上面的描述也许有点模糊,举几个例子就知道了。
这个例子里元素的DOM属性有“href、target和class",这些属性就是元素本身就带有的属性,也是W3C标准里就包含有这几个属性,或者说在IDE里能够智能提示出的属性,这些就叫做固有属性。处理这些属性时,建议使用prop方法。
这个例子里元素的DOM属性有“href、id和action”,很明显,前两个是固有属性,而后面一个“action”属性是我们自己自定义上去的,元素本身是没有这个属性的。这种就是自定义的DOM属性。处理这些属性时,建议使用attr方法。使用prop方法取值和设置属性值时,都会返回undefined值。
再举一个例子:
是否可见
是否可见像checkbox,radio和select这样的元素,选中属性对应“checked”和“selected”,这些也属于固有属性,因此需要使用prop方法去操作才能获得正确的结果。
$("#chk1").prop("checked") == false $("#chk2").prop("checked") == true
如果上面使用attr方法,则会出现:
$("#chk1").attr("checked") == undefined $("#chk2").attr("checked") == "checked"
希望本文所述对大家jQuery程序设计有所帮助。
- を取得し、スタイルを設定します。
- の設定 ID を取得します。
- 設定クラスを取得します。

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft