jQuery常用属性方法大全 attr(),val()
@@@@属性篇:
写作本篇文章的意义:jQuery的教程千千万,却没有英文版的API讲的系统、到位,一些话用中文翻译过来味道就变了,所以我将英文版的API的一些常用的方法单独提出来放在这里,并用自己的实践+理解陈述,在大家懒得查看官网的时候可以做为参考。
属性的作用的原文描述:These methods get and set DOM attributes of elements.即用来获取/设置DOM元素的属性的值;我们经常需要在页面中从元素中取值和设值,这些方法使用频次“非常高”!所以掌握它是成为牛逼工程师必须的基本功啦!
|||||| .addClass()
Description: Adds the specified class(es) to each element in the set of matched elements.
添加指定的类到匹配元素集合中的每一个元素。
1、.addClass(className)
类型:String
一个或多个类(用空格隔开)添加到匹配的元素的class属性。
2、.addClass(function)
类型:Function(Integer index , String currentClassName)==>String
$("p").addClass("myClass yourClass");
②切换元素的类从一个到另一个:
$("p").removeClass("myClass noClass").addClass("yourClass");
所有p段落中的myClass和noClass都被移除,yourClass则被加入到所有匹配的p元素中。
③接收一个function函数:
$("ul li").addClass(function( index ){
return "item-"+index;
})
如果给定无序列表中的两个<li>元素,那么上面的函数的作用是将在第一个<li>中加入item-0类,第二个<li>中加入item-1类。
|||||| .attr()
Description:Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.
获取匹配元素集合的属性的第一个元素的值,或者设置一个或多个属性给匹配的每个元素。
.attr(attributeName);//只获取匹配元素集合的第一个元素的属性值,想要获取多个值可以利用jQuery的.each()或.map()方法
.attr(attributeName,value);//给制定的属性设置值
①获取属性值:
<body>
<input id="check1" checked="checked" type="checkbox" />
<label for="check1" >check me</label> <script>
$("input").change(function(){
var $input=$("input[id='check1']");
$("p").html("通过.attr('checked')获取checked的值:"+$input.attr("checked")+<br>
"通过.prop('checked')获取checked的属性值:"+$input.prop("checked")+<br>
"通过.is(':checked')获取checked的属性值:"+$input.is(":checked")+<br>
}
</script>
</body> 结果: Check me .attr( 'checked' ): checked//取值
.prop( 'checked' ): true//判断
.is( ':checked' ): true//判断
上面针对checkbox的情况,相对比较特殊,.attr()是取得属性的值,.prop()在checked, selected, disabled三个DOM元素属性取值时,返回的结果是布尔型,其他情况下都是返回属性值。
示例:
<style>
em {
color: blue;
font-weight: bold;
}
div {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Once there was a <em title="huge, gigantic">large</em> dinosaur...</p>
The title of the emphasis is:<div></div>
<script>
var title = $( "em" ).attr( "title" );
//var title=$("em").prop("title");与.attr()效果一样
$( "div" ).text( title );
</script>
当设置checkbox的选中情况时:
<body> <input type="checkbox" checked="checked">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox" checked="checked"> <script>
$( "input[type='checkbox']" ).attr("checked",false);
$("input[type='checkbox']").prop("checked",false);//与.attr()效果一样
</script> </body>
②设置属性值:
.attr(attributeName,value):这种方法设置属性值非常方便,且看:
<img id="greatPhoto" src="1.jsp" alt="this is a photo" />
<script>
$("#greatPhoto").attr("alt","come form my world!");
</script>
设置多个属性值:
$( "#greatPhoto" ).attr({
alt: "Beijing Brush Seller",
title: "photo by Kelly Clark"
});
用函数来设置值:
<scirpt>
$("#greatephoto").attr(function( i , val){//获取第i个id值为greatphoto的变量值val,此处的i即是id的索引值,val为其对应的id值
return val+"change";
})
</script>
设置id的div基于页面中的位置:
<body> <div>Zero-th <span></span></div>
<div>First <span></span></div>
<div>Second <span></span></div> <script>
$("div").attr("id".function(arr){//设置id的属性值,arr的值即是id属性的值,此处没有用变量i来对应,因为下面用了.each()来循环设置
return arr+"div-id";
}).each(function(){//循环追加信息
$("span",this).html("id='<b>"+this.id+"</b>'");//this指代当前循环的"span"对象
})
</script> </body>
|||||| .hasClass()
Description: Determine whether any of the matched elements are assigned the given class.
用来判断是否有匹配的类。应用相对比较简单,看例即知:
<div id="mydiv" class="foo bar"></div>
//判断是否含有类
$( "#mydiv" ).hasClass( "foo" )
|||||| .html()
Description: Get the HTML contents of the first element in the set of matched elements.
用来获取匹配的元素集合的第一个元素的文本内容。
<div class="demo-container">
<div class="demo-box">Demonstration Box</div>
</div>
//获取div中的内容
$( "div.demo-container" ).html();
当.html()方法中输入内容时,则会改变对应元素的文本内容。
|||||| .removeAttr()
Description: Remove an attribute from each element in the set of matched elements.
清除所有匹配的元素集合的元素。
.removeAttr()方法是从javascript中的.removeAttribute()继承过来,但是jQuery的此方法可以在不同版本的浏览器上运行。
.removeAttr(attributeName)需要的类型是String类型:
下面这个例子比较经典,略带一点逻辑:
<button>Change title</button>
<input type="text" title="hello there">
<div id="log"></div> <script>
(function() {
var inputTitle = $( "input" ).attr( "title" );
$( "button" ).click(function() {
var input = $( this ).next();//选择同级元素的下一个元素,也就是下面那个div标签对象 if ( input.attr( "title" ) == inputTitle ) {//如果div对象的title值与input对象的title值相同就清除div对象的title属性值,不相同的情况下则添加input对象的title属性值给div对象
input.removeAttr( "title" )
} else {
input.attr( "title", inputTitle );
} $( "#log" ).html( "input title is now " + input.attr( "title" ) );
});
})();
</script>
.removeAttr()与.removeProp()的作用基本相似。
|||||| .val()
Description: Get the current value of the first element in the set of matched elements.
获取匹配元素集合的第一个元素的值。
注意事项:The .val() method is primarily used to get the values of form elements such as input, select and textarea. When called on an empty collection, it returns undefined.
通常用于input、select、textarea。
//获取下拉框的foo类中被选中的项的值
$( "select.foo option:selected").val(); // 获取所有foo类的下拉框的值
$( "select.foo" ).val(); // 获取被选中的复选框的值
$( "input:checkbox:checked" ).val(); // 获取被选中的单选按钮的值
$( "input:radio[name=bar]:checked" ).val();
下面的例子实现:单选下拉框显示选项的值,多选下拉框显示选中项的值:
<p></p> <select id="single">
<option>Single</option>
<option>Single2</option>
</select> <select id="multiple" multiple="multiple">
<option selected="selected">Multiple</option>
<option>Multiple2</option>
<option selected="selected">Multiple3</option>
</select> <script>
function displayVals(){
var singleVal=$("#single").val();
var multipleVals=$("#multiple").val()|| [];//这样写也可以:var multipleVals=$("#multiple").val();
$("p").html(singleVal+" "+multipleVals.join(","));
} displayVals();//调用displayVal()方法 $("select").change(displayVals);//当select对象的选项改变时,调用change方法,调用displayVals()方法,如果不加此行,则在变换的时候,不会调用displayVal()这个方法。
</script>
从input对象中取值:
<div>
<input type="text" value="some words" />
<p></p>
</div>
<script>
$("input").keyup(function(){
var inputValue=$(this).val();
$("p").text(inputValue);
}).keyup();
</script>
||| .val(value)、.val(function)
Description: Set the value of each element in the set of matched elements.
给匹配元素集合的每一个元素设值。
① 点击各个button后将其文本值赋给input对象的文本域:
<div>
<button>Filed1</button>
<button>Filed0</button>
<button>Filed1</button>
<input type="text" />
</div>
<script>
$("button").click(function(){
$("input").val($(this).text());
})
</script>
②使用函数声明修改Input对象的值:
<div>
<input type="text" value="do something"/>
<input type="text" value="do something"/>
<input type="text" value="do something"/>
</div>
<script>
$("input").blur(function(){//当Input对象失去焦点的时候,函数开始
$(this).val(function(i,val){//取得第i个input对象的value值
return val.toUpperCase();//把这个值转换成大写
}) ;
})
</script>
至此,所有jQuery的常用属性类方法已经整理完毕。
jQuery常用属性方法大全 attr(),val()的更多相关文章
- JS常用属性方法大全
1. 输出语句 : document.write(""); 2.JS 中的注释为 : // 3. 传统的 HTML 文档顺序是 : document->html->(h ...
- js与jquery常用数组方法总结
昨天被问数组方法的时候,问到sort()方法是否会改变原来的数组.本来我猜是不会,也是这么说,马上我又觉得,知识这种东西,不确定的时候直接说不确定或不知道就好,只是凭借着不确定的猜测或者是记忆,害人害 ...
- jQuery 常用核心方法
jQuery 常用核心方法 .each() 遍历一个jQuery对象,为每个匹配元素执行一个函数 $('p').each(function(idx,node){ $(node).text(idx + ...
- Java获取各种常用时间方法大全
Java获取各种常用时间方法大全 package cc.javaweb.test; Java中文网,Java获取各种时间大全 import java.text.DateFormat; import j ...
- Delphi中TStringList类常用属性方法详解
TStrings是一个抽象类,在实际开发中,是除了基本类型外,应用得最多的. 常规的用法大家都知道,现在来讨论它的一些高级的用法. 先把要讨论的几个属性列出来: 1.CommaText 2.Delim ...
- WebBrowser常用属性方法介绍
WebBrowser 常用属性方法 ■■方法 ============================== ▲GoBack 相当于IE的"后退"按钮,使你在当前历史列表中后 ...
- js如何操作表格(常用属性方法汇总)
js如何操作表格(常用属性方法汇总) 一.总结 一句话总结: 二.表格相关的属性和方法 1.1 Table 对象集合 cells[] 返回包含表格中所有单元格的一个数组. 语法:tableObject ...
- express模块中的req,res参数的常用属性方法
express模块中的req,res参数的常用属性方法 const express = require('express'); const router = express.Router() rout ...
- [Jquery] 操作html 不常用元素方法大全
除http://www.w3school.com.cn/jquery/jquery_selectors.asp上的以外该大全应都有. 第一章 input控件篇 1.操作select 下拉框 1.1 获 ...
随机推荐
- 雷林鹏分享:Ruby Socket 编程
Ruby Socket 编程 Ruby提供了两个级别访问网络的服务,在底层你可以访问操作系统,它可以让你实现客户端和服务器为面向连接和无连接协议的基本套接字支持. Ruby 统一支持应用程的网络协议, ...
- js 文件系统API操作示例
最近有个需求是:自动抓取某网站登录页面的验证码图片并保存,抓取n次.使用chrome插件来实现,其中使用到了js操作文件系统的api,特将代码记录下来,以备查阅. PS:第一次使用js文件系统的api ...
- HDU 2276 矩阵快速幂
Kiki & Little Kiki 2 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java ...
- 安装MySQL后要做的事
安装MySQL后要修改的配置 [mysql] default-character-set=utf8 [mysqld] # 关闭域名反解 skip_name_resolve # 每表一个独立的表空间文件 ...
- 64位Ubuntu系统安装OpenCV 2.4.x+ffmpeg 完美解决方案
http://www.bfcat.com/index.php/2012/09/64bits-ubuntu-opencv-2-4-x-ffmpeg/
- HDU 2612 Find a way bfs 难度:1
http://acm.hdu.edu.cn/showproblem.php?pid=2612 bfs两次就可将两个人到达所有kfc的时间求出,取两人时间之和最短的即可,这个有点不符合实情,题目应该出两 ...
- javascript递归导致的堆栈溢出
function foo() {foo(); //setTimeout(foo, 0); } foo() 原因是每次执行代码时,都会分配一定尺寸的栈空间(Windows系统中为1M),每次方法调用 ...
- ubuntu14.04安装Android Studio出现error while loading shared libraries: libz.so.1的解决方法
参考博客地址: http://blog.csdn.net/newairzhang/article/details/28656693 安装lib32z1就可以解决,如下: 首先,sudo apt-get ...
- python爬虫错误
错误描述 TypeError: list indices must be integers or slices, not str 错误缘由 取标签属性的时候, find_all()函数与find()函 ...
- python requests 设置headers 和 post请求体x-www-form-urlencoded
1.application/json:是JSON格式提交的一种识别方式.在请求头里标示.2.application/x-www-form-urlencoded : 这是form表单提交的时候的表示方式 ...