设置内容 - text()、html() 以及 val()
text()、html() 以及 val() 的回调函数
- text()、html() 以及 val(),同样拥有回调函数。回调函数有两个参数:被选元素列表中当前元素的下标,以及原始(旧的)值。然后以函数新值返回您希望使用的字符串。
-
$("#btn1").click(function(){
$("#test1").text(function(i,origText){
return "旧文本: " + origText + " 新文本: Hello world! (index: " + i + ")";
});
});
$("#btn2").click(function(){
$("#test2").html(function(i,origText){
return "旧 html: " + origText + " 新 html: Hello <b>world!</b> (index: " + i + ")";
});
});
设置属性 - attr()
- jQuery attr() 方法也用于设置/改变属性值。
-
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#runoob").attr({
"href" : "http://www.runoob.com/jquery",
"title" : "jQuery 教程"
});
// 通过修改的 title 值来修改链接名称
title = $("#runoob").attr('title');
$("#runoob").html(title);
});
});
</script>
</head>
<body>
<p><a href="//www.runoob.com" id="runoob">菜鸟教程</a></p>
<button>修改 href 和 title</button>
<p>点击按钮修改后,可以查看 href 和 title 是否变化。</p>
</body>
</html>
转载于:https://my.oschina.net/u/4159909/blog/3072806