1.获取内容直接.xxx(xxx为text、html、val)
$("#btn1").click(function(){
alert("Text: " + $("#test").text());
<pre name="code" class="html"> alert("HTML: " + $("#test").html());
<pre name="code" class="html"> alert("Value: " + $("#test").val());
<pre name="code" class="html"> alert($("#w3s").attr("href"));
});
- text() - 设置或返回所选元素的文本内容
- html() - 设置或返回所选元素的内容(包括 HTML 标记)
- val() - 设置或返回表单字段的值
- attr() 方法用于获取属性值。
$("#btn1").click(function(){
$("#test1").text("Hello world!");
<pre name="code" class="html" style="font-size: 13.3333px;"> $("#test2").html("<b>Hello world!</b>");
<pre name="code" class="html" style="font-size: 13.3333px;"> $("#test3").val("Dolly Duck");
});
3、增加新内容/元素
- append() - 在被选元素的结尾插入内容
- prepend() - 在被选元素的开头插入内容
- after() - 在被选元素之后插入内容
- before() - 在被选元素之前插入内容
$("p").append("Some appended text.");
$("p").prepend("Some prepended text.");
<pre name="code" class="html"><!DOCTYPE html>
<html>
<head>
<script src="/jquery/jquery-1.11.1.min.js"></script>
<script>
function appendText()
{
var txt1="<p>Text.</p>"; // 以 HTML 创建新元素
var txt2=$("<p></p>").text("Text."); // 以 jQuery 创建新元素
var txt3=document.createElement("p");
txt3.innerHTML="Text."; // 通过 DOM 来创建文本
$("body").append(txt1,txt2,txt3); // 追加新元素
}
</script>
</head>
<body>
<p>This is a paragraph.</p>
<button οnclick="appendText()">追加文本</button>
</body>
</html>
//befor、after
$("img").after("Some text after");
$("img").before("Some text before");
4、删除元素(remove empty)
remove() 方法删除被选元素及其子元素;empty() 方法删除被选元素的子元素。
示例:
$("#div1").remove();
<pre name="code" class="html">$("#div1").empty();
$("p").remove(".italic"); //<span style="font-family: Verdana, Arial, 宋体; font-size: 12px; line-height: 18px; background-color: rgb(249, 249, 249);">删除 class="italic" 的所有 <p> 元素</span>
5、添加、删除类(addClass removeClass toggleClass)
- addClass() - 向被选元素添加一个或多个类
- removeClass() - 从被选元素删除一个或多个类
- toggleClass() - 对被选元素进行添加/删除类的切换操作
.important
{
font-weight:bold;
font-size:xx-large;
}
.blue
{
color:blue;
}
<pre name="code" class="html">$("button").click(function(){
$("h1,h2,p").addClass("blue");
$("div").addClass("important");
<pre name="code" class="html"> $("#div1").addClass("important blue");
});
6、设置css属性
获取css属性:
$("p").css("background-color");
设置css属性:
$("p").css("background-color","yellow");
<pre name="code" class="html">$("p").css({"background-color":"yellow","font-size":"200%"});
7、设置尺寸
- width() //宽度(不包括内边距、边框或外边距)
- height() //元素的高度(不包括内边距、边框或外边距)
- innerWidth() //元素的宽度(包括内边距)
- innerHeight() //元素的高度(包括内边距)
- outerWidth() //元素的宽度(包括内边距和边框)
- outerHeight() //元素的高度(包括内边距和边框)
获取:
$("button").click(function(){
var txt="";
txt+="Document width/height: " + $(document).width();
txt+="x" + $(document).height() + "\n";
txt+="Window width/height: " + $(window).width();
txt+="x" + $(window).height();
alert(txt);
});
设置:
$("#div1").width(500).height(500);