jquery安装
- 下载jquery的js包后,用script标签引入
语法
简介
- jQuery 语法是通过选取 HTML 元素,并对选取的元素执行某些操作。
为了防止文档在完全加载(就绪)之前运行 jQuery 代码,即在 DOM 加载完成后才可以对 DOM 进行操作。通常jQuery代码写在如下的代码块中。
$(document).ready(function(){
});
$(function(){
});
选择器
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});
$(document).ready(function(){
$("button").click(function(){
$(".test").hide();
});
});
$("*")
$(this)
$("p.intro")
$("p:first")
$("ul li:first")
$("ul li:first-child")
$("[href]")
$("a[target='_blank']")
$("a[target!='_blank']")
$(":button")
$("tr:even")
$("tr:odd")
常用的 jQuery 事件方法
$("p").click(function(){
$(this).hide();
});
$("p").dblclick(function(){
$(this).hide();
});
$("#p1").mouseenter(function(){
alert('您的鼠标移到了 id="p1" 的元素上!');
});
$("#p1").mouseleave(function(){
alert("再见,您的鼠标离开了该段落。");
});
$("#p1").mousedown(function(){
alert("鼠标在该段落上按下!");
});
$("#p1").mouseup(function(){
alert("鼠标在段落上松开。");
});
$("#p1").hover(
function(){
alert("你进入了 p1!");
},
function(){
alert("拜拜! 现在你离开了 p1!");
}
);
$("input").focus(function(){
$(this).css("background-color","#cccccc");
});
$("input").blur(function(){
$(this).css("background-color","#ffffff");
});
jQuery 效果
$("#hide").click(function(){
$("p").hide();
});
$("#show").click(function(){
$("p").show();
});
$("button").click(function(){
$("p").toggle();
});
$("button").click(function(){
$("#div1").fadeIn();
$("#div2").fadeIn("slow");
$("#div3").fadeIn(3000);
});
$("button").click(function(){
$("#div1").fadeOut();
$("#div2").fadeOut("slow");
$("#div3").fadeOut(3000);
});
$("button").click(function(){
$("#div1").fadeToggle();
$("#div2").fadeToggle("slow");
$("#div3").fadeToggle(3000);
});
获取内容和属性
- 获得内容 - text()、html() 以及 val()
$("#btn1").click(function(){
alert("Text: " + $("#test").text());
});
$("#btn2").click(function(){
alert("HTML: " + $("#test").html());
});
$("#btn1").click(function(){
alert("值为: " + $("#test").val());
});
$("button").click(function(){
alert($("#runoob").attr("href"));
});
添加元素
- append() 方法在被选元素的结尾插入内容(仍然在该元素的内部)。
$("p").append("追加文本");
- prepend() 方法在被选元素的开头插入内容。
$("p").prepend("在开头追加文本");
删除元素
$("#div1").remove();
$("#div1").empty();