JQuery获取设置内容及属性
JQuery捕获内容和属性
①获取文本内容——text()、html()、val()
text():设置或返回所选元素的文本内容
html():设置或返回所选元素的内容(包括html标记)
val():设置或返回表单字段的值
实例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<title>get Text</title>
<link rel="stylesheet" href="">
<style>
div{
color: #aa3a4f;
font-size: 23px;
}
</style>
<script src="http://libs.baidu.com/jquery/2.0.3/jquery.min.js"></script>
<script>
$(function () {
var text=$('div').text();//获取所选元素文本值
$('div').text('this is a new text'); //设置所选元素的文本值
alert('The Text is: '+text); //弹出原文本值
var text2=$('div').text()
alert('The New Text is: '+text2) //弹出新文本值
var text=$('div').html(); //获取所选元素文本值
alert('The Text is: '+text);
$('div').html('<i>this is a new text</i>'); //重新设置所选元素的内容,并倾斜文本
var text2=$('div').html();
alert('The New Text is: '+text2) //html()会返回html标记
var text=$('input').val(); //获取所选表单字段值
alert('The Value is: '+text+' !');
$('input').val('Hello new World'); //设置所选表单字段值
var text2=$('input').val();
alert('The New Value is: '+text2+' !')
})
</script>
</head>
<body>
<div>this is a text</div>
<input type="text" value="Hello World">
</body>
</html>
标注:以上方法设置所选元素内容时,括号里面是可以设置回调函数的,不单是字符串!
②获取属性
attr():该方法用来获取所选元素的属性值
实例:
<script src="http://libs.baidu.com/jquery/2.0.3/jquery.min.js"></script>
<script>
$(function () {
var href=$('a').attr('href');
alert(href);
})
</script>
</head>
<body>
<a href="http://www.baidu.com/">This is a Link</a>
</body>
同样的,attr()方法也允许设置属性值,也允许同时设置多个属性值,例如:
<script src="http://libs.baidu.com/jquery/2.0.3/jquery.min.js"></script>
<script>
$(function () {
$('a').attr({ //设置多个属性值的时候,要用{}括起来,以键值对的形式书写,各属性之间用“,”隔开
'href':'http://blog.csdn.net/',
'title':'the new title'
});
var href=$('a').attr('href');
alert(href);
})
</script>
</head>
<body>
<a href="http://www.baidu.com/" title="click me">This is a Link</a>
</body>
attr()同样支持回调函数,回调函数由两个参数:被选元素列表中当前元素的下标,以及原始(旧的)值。然后以函数新值返回你希望使用的字符串
实例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Attr()</title>
<script src="//libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#school").attr("href", function(i, origValue){
return origValue + "/jquery";
});
});
});
</script>
</head>
<body>
<p><a href="http://blog.csdn.net/" id="school">CSDN论坛</a></p>
<button>修改 href值</button>
<p>点击按钮修改后,可以点击链接查看 href 属性是否变化。</p>
</body>
</html>
还没有评论,来说两句吧...