jquery获取自定义属性(attr和prop)实例介绍

$("form").attr("check"); $("form").prop("check"); 两种都可以,不过新版jquery推荐第二种,两个在其他方面都差不多,我发现的唯一不同就是在checkbox上的时候,需要用prop,不然IE浏览器会不兼容

复制代码 代码如下:


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<scripttype="text/javascript"src="/js/jq1.3.2.js"></script>
</head>
<body>
<divlang="rrery"> </div>
<divdata-url="rrery"> </div>
<divdata-url="rrrrrrrrrrrrrrttttttttttttttttttttttgggggggggggggggggggggg"> </div>
<divdata-url="rrrrrrrrrrrrrrrrrrrrrrrrrrttttttttttttttttt777777777777777777777777777777777778888888888455rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrtttttttttttttttttttttttttttt777777777777777777777777777777777778888888888888"> </div>
</body>
</html>
<script>
// var J = $("div[lang]").get();
// alert($("[data-url]:eq(2)").attr("data-url"));
$("[data-url]").each(function () {
alert($(this).attr("data-url")); });
// $("[data-url]").each(function () {
// alert($(this).prop("data-url")); // });
</script>


附:jquery attr()方法

jquery中用attr()方法来获取和设置元素属性,attr是attribute(属性)的缩写,在jQuery DOM操作中会经常用到attr(),attr()有4个表达式。

1. attr(属性名       //获取属性的值(取得第一个匹配元素的属性值。通过这个方法可以方便地从第一个匹配元素中获取一个属性的值。如果元素没有相应属性,则返回 undefined )

2. attr(属性名, 属性值)   //设置属性的值 (为所有匹配的元素设置一个属性值。)

3. attr(属性名,函数值    //设置属性的函数值  (为所有匹配的元素设置一个计算的属性值。不提供值,而是提供一个函数,由这个函数计算的值作为属性值。)

4.attr(properties)    //给指定元素设置多个属性值,即:{属性名一: “属性值一” , 属性名二: “属性值二” , … … }。(这是一种在所有匹配元素中批量设置很多属性的最佳方式。 注意,如果你要设置对象的class属性,你必须使用'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="https://www.jb51.net/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)获取title值:

复制代码 代码如下:


<script>
alert($("ul li:eq(1)").attr("title"));
</script>


结果:

jquery获取自定义属性(attr和prop)实例介绍

1.2使用attr(name)获取alt值:

复制代码 代码如下:


<script>
alert($("ul li:eq(1)").attr("alt"));
</script>


结果:

jquery获取自定义属性(attr和prop)实例介绍



2. attr(name,value)   //设置属性的值


2.1使用attr(name,value)修改title值为:不吃橘子

复制代码 代码如下:


<script>
$("ul li:eq(1)").attr("title","不吃橘子");
alert($("ul li:eq(1)").attr("title"));
</script>


结果:

jquery获取自定义属性(attr和prop)实例介绍



3. attr(name,fn)  //设置属性的函数值

3.1把alt属性的值设置为title属性的值。

复制代码 代码如下:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wdgfpz.html