简单的事件绑定
click()
blur()
hover() :mouseenter + mouseleave
focus()
keyup()
mouseup()
mousedown()
………..
on 方式 绑定
//绑定一个方法
$( "#dataTable tbody tr" ).on( "click", function() {
console.log( $( this ).text() );
});
//给子元素绑定事件
$( "#dataTable tbody" ).on( "click", "tr", function() {
console.log( $( this ).text() );
});
//绑定多个事件的方式
$( "div.test" ).on({
click: function() {
$( this ).toggleClass( "active" );
}, mouseenter: function() {
$( this ).addClass( "inside" );
}, mouseleave: function() {
$( this ).removeClass( "inside" );
}
off 解绑
$( “body” ).off( “click”, “p”, foo );
function foo () {
// Code to handle some kind of event
};
$( “p” ).off(); // 移除所有事件
$( "body" ).on( "click", "p", foo );
// ... Foo will no longer be called.
$( "body" ).off( "click", "p", foo );
bind unbind 绑定与解绑
$( “p” ).bind(“click.name”,fn);
$(“p”).unbind(“click.name”,fn);
事件委托
delegate 代理 / 委托
第一个参数表示:选择器(给哪个子元素绑定事件)
第二个参数表示:事件类型
第三个参数表示:回调
$("p").delegate("input", "click", function () {
alert($(this).val());
});
事件对象
查看事件对象
$("input").on("click", function (e) {
console.log(e);
});
阻止默认行为:
$("a").click(function (e) {
// 阻止默认行为
e.preventDefault();
});
阻止冒泡:
$("#j_btnClick").click(function (e) {
alert("我是内容");
e.stopPropagation();
});
链式编程
end()表示结束当前链最近的一次过滤操作,并返回匹配元素之前的状态
$("div")
.children("p") // 过滤操作
.children("span") // 过滤操作
.css("color", "red")
.end() // 结束当前链最近的一次过滤操作,并且返回匹配元素之前的状态。
.css("background", "pink");
隐式迭代
$("div").css({
height: "200px",
background: "red",
"margin-bottom": "20px"
});
var html = $("div").html();
console.log(html);
<div>第一个</div>
<div>第二个</div>
each函数
全局的
$.each(array, function(index, object){})
$(“li”).each(function(index, element){} )
参数的顺序是一致的。
例如:
$( "li" ).each(function() {
$( this ).addClass( "foo" );
});
$( "li" ).each(function( index ) {
console.log( index + ": " + $( this ).text() );
});
$( "div" ).each(function( index, element ) {});
index:选择器的位置
element:当前的元素(也可使用this)
map函数
$.map(arry,function(object,index){}) (注意参数的顺序是反的) 返回一个新的数组
var arry = $(“li”).map(function(index, element){})
var newArr = $.map($("li"), function(e, i) {
return $(e).text() + i;//每一项返回的结果组成新数组
});
var newArr = $("li").map(function(index, ele){
console.log("elem:" + elem);
console.log("index:" + index);
retrun index;
});
jquery的ajax
JQ版处理 JSONP
JQ版 cookie