1.JQuery获取
获得内容 - text()、html() 以及 val()
text() - 设置或返回所选元素的文本内容
html() - 设置或返回所选元素的内容(包括 HTML 标记)
val() - 设置或返回表单字段的值
<html>
<head>
<script type="text/javascript"src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"></script>
<script>
$(document).ready(function () {
$("button").click(function () {
alert("Values:" + $("#test").val());
});
});
</script>
</head>
<body>
<p>姓名:<input type="text"id="test"value="" /></p>
<button>显示</button>
</body>
</html>
获取属性 - attr()
jQuery attr() 方法用于获取属性值。
2.JQuery设置内容和属性
text()、html() 以及 val() 的回调函数
上面的三个 jQuery 方法:text()、html() 以及 val(),同样拥有回调函数。回调函数由两个参数:被选元素列表中当前元素的下标,以及原始(旧的)值。然后以函数新值返回您希望使用的字符串。
3.添加元素
append() - 在被选元素的结尾插入内容
$("p").append("Some appended text.");
prepend() - 在被选元素的开头插入内容
$("p").prepend("some prepended text");
after() - 在被选元素之后插入内容
$("")
before() - 在被选元素之前插入内容
4.删除元素
remove() - 删除被选元素(及其子元素)
$("div").remove();
empty() - 从被选元素中删除子元素
<script>
$(document).ready(function () {
$("button").click(function () {
$("#div1").empty();
});
});
</script>
</head>
<body>
<div id="div1" style="height:100px;width:300px;border:1px solid black;background-color:yellow;">
This is some text in the div.
<p>This is a paragraph in the div.</p>
<p>This is another paragraph in the div.</p>
</div>
<br>
<button>清空 div 元素</button>
</body>
注:清楚div中的元素但不会清楚div
过滤被删除的元素
jQuery remove() 方法也可接受一个参数,允许您对被删元素进行过滤。
该参数可以是任何 jQuery 选择器的语法。
下面的例子删除 class=“italic” 的所有
元素:
$("p").remove(".italic");
JQuery获取并设置CSS类
addClass() - 向被选元素添加一个或多个类
$("button").click(function(){
$("h1,h2,p").addClass("blue");
$("div").addClass("important");
});
removeClass() - 从被选元素删除一个或多个类
toggleClass() - 对被选元素进行添加/删除类的切换操作
$("button").click(function(){
$("h1,h2,p").toggleClass("blue");
});
css() - 设置或返回样式属性
$("p").css("background-color");
设置css属性
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").css("background-color","yellow");
});
});
</script>
</head>
<body>
<h2>这是标题</h2>
<p style="background-color:#ff0000">这是一个段落。</p>
<p style="background-color:#00ff00">这是一个段落。</p>
<p style="background-color:#0000ff">这是一个段落。</p>
<p>这是一个段落。</p>
<button>设置 p 元素的背景色</button>
JQuery尺寸
通过 jQuery,很容易处理元素和浏览器窗口的尺寸。
jQuery width() 和 height() 方法
width() 方法设置或返回元素的宽度(不包括内边距、边框或外边距)。
height() 方法设置或返回元素的高度(不包括内边距、边框或外边距)。
下面的例子返回指定的
<script>
$(document).ready(function () {
$("button").click(function () {
var txt = "";
txt += "width of div" + $("#div1").width() + "</br>"
txt += "height of div" + $("#div1").height();
$("#div1").html(txt);
});
});
</script>
</head>
<body>
<div id="div1" style="height:100px;width:300px;border:1px solid black;background-color:yellow;">
</div>
jQuery outerWidth() 和 outerHeight() 方法
元素的宽度和高度包括内边距和边框