$(“button”).click(function(){
$(“#w3s”).attr(“href”,“http://www.w3school.com.cn/jquery”);
});
attr() 方法也允许您同时设置多个属性。
下面的例子演示如何同时设置 href 和 title 属性:
$(“button”).click(function(){
$(“#w3s”).attr({
“href” : “http://www.w3school.com.cn/jquery”,
“title” : “W3School jQuery Tutorial”
});
});
- jQuery 方法 attr(),也提供回调函数。
回调函数由两个参数:被选元素列表中当前元素的下标,以及原始(旧的)值。
然后以函数新值返回您希望使用的字符串。
$(“button”).click(function(){
$(“#w3s”).attr(“href”, function(i,origValue){
return origValue + “/jquery”;
});
});
(三)jQuery添加和删除元素
1.添加新内容的四个 jQuery 方法:
• append() - 在被选元素的结尾插入内容(内)
$(“ol”).append(“
- Appended item
- ”);
• prepend() - 在被选元素的开头插入内容(内)
$(“p”).prepend(“Some prepended text.”);
append() 和 prepend() 方法能够通过参数接收无限数量的新元素。
• after() - 在被选元素之后插入内容(外)
• before() - 在被选元素之前插入内容(外)
$(“img”).after(“Some text after”);
$(“img”).before(“Some text before”);
after() 和 before() 方法能够通过参数接收无限数量的新元素。
2. 如需删除元素和内容,一般可使用以下两个 jQuery 方法:
• remove() - 删除被选元素(及其子元素)
$(“#div1”).remove();
• empty() - 从被选元素中删除子元素
$(“#div1”).empty();
过滤删除:jQuery remove() 方法也可接受一个参数,允许您对被删元素进行过滤。
下面的例子删除
class="italic"
的所有<p>
元素:$(“p”).remove(“.italic”);
(四)jQuery css类及css()
1.jQuery 拥有若干进行 CSS 操作的方法:
• addClass() - 向被选元素添加一个或多个类
$(“button”).click(function(){
$(“h1,h2,p”).addClass(“blue”);
$(“#div1”).addClass(“important blue”);
});
• removeClass() - 从被选元素删除一个或多个类
$(“button”).click(function(){
$(“h1,h2,p”).removeClass(“blue”);
});
• toggleClass() - 对被选元素进行添加/删除类的切换操作
$(“button”).click(function(){
$(“h1,h2,p”).toggleClass(“blue”);
});
• css() - 设置或返回样式属性
2. jQuery css() 方法
css() 方法设置或返回被选元素的一个或多个样式属性。
(1)返回 CSS 属性,返回首个匹配元素的 background-color 值
$(“p”).css(“background-color”);
(2)设置 CSS 属性
$(“p”).css(“background-color”,“yellow”);
(3)设置多个属性
css({“propertyname”:“value”,“propertyname”:“value”,…});
面的例子将为所有匹配元素设置 background-color 和 font-size:
$(“p”).css({“background-color”:“yellow”,“font-size”:“200%”});
(五)jQuery 尺寸
通过 jQuery,很容易处理元素和浏览器窗口的尺寸。
jQuery 提供多个处理尺寸的重要方法:
• width()方法设置或返回元素的宽度(不包括内边距、边框或外边距)。
• height()方法设置或返回元素的高度(不包括内边距、边框或外边距)。
• innerWidth()方法返回元素的宽度(包括内边距)。
• innerHeight()方法返回元素的高度(包括内边距)。
• outerWidth()方法返回元素的宽度(包括内边距和边框)。outerWidth(true) 方法返回元素的宽度(包括内边距、边框和外边距)。
• outerHeight()方法返回元素的高度(包括内边距和边框)。outerHeight(true) 方法返回元素的高度(包括内边距、边框和外边距)。
显示 div 的尺寸height:200px–width:500px–padding–10px–margin:3px–border:1px
width() - 返回元素的宽度。
height() - 返回元素的高度。
innerWidth() - 返回元素的宽度(包括内边距)。
innerHeight() - 返回元素的高度(包括内边距)。
outerWidth() - 返回元素的宽度(包括内边距和边框)。
outerHeight() - 返回元素的高度(包括内边距和边框)。
outerWidth(true) - 返回元素的宽度(包括内边距、边框和外边距)。
outerHeight(true) - 返回元素的高度(包括内边距、边框和外边距)。
效果如下图
下面的例子返回文档(HTML 文档)和窗口(浏览器视口)的宽度和高度:
$(“button”).click(function(){
var txt=“”;