jQuery
部分函数
$('#MyTable tr').toggle(
function () {
$(this).css('background-color', '#efefef');
},
function () {
$(this).css('background-color', '#efefef');
}
function () {
$(this).css('background-color', 'Yellow');
}
);
$('#myTable tr').hover(
$(this).toggleClass('LightHighlight');
);
$('#myTable tr').hover(
function () {
//mousenter
$(this).css('background-color', '#efefef');
},
function () {
//mouseleave
$(this).css('background-color', '#fff');
}
);
$(document).ready(
function () {
var tbody = $('#myTable tbody');
tbody.on('click', 'td', function(){
alert($(this).text());
});
}
);
var table = $('#myTable");
//var tbody = table.find('tbody');
table.find('tbody').on('click', function () {
//
});
$(document).ready(function () {
$('tr').on('click mouseenter mouseleave', function (e) {
alert($(this).html());
if (e.type == 'mouseup') {
//如果是鼠标点击事件,获取点击位置
$(this).text('X: ' + e.pageX + ' Y: ' + e.pageY);
}
});
});
$('tr').on({
click: function () {
},
mouseenter: function () {
},
mouseleave: function () {
},
mouseup: function (e) {
}
});
$("#myDiv").mounseenter(function () {
//
})
.mouseleave(function () {
//
})
.mouseup(funtion (e) {
//
});
$('.MyInput').change(function () {
alert($(this).val());
$(this).addClass('Highlight');
});
var button = document.getElementById('SubmitButton');
if (document.addEventListener) { //大多数浏览器为true
//dom元素绑定click事件,事件名前无需+on
button.addEventListener('click', myFunction, false);
} else if (document.attachEvent) { //仅ie8及以下的浏览器为true
//dom元素绑定click事件,事件名前需要+on
button.attachEvent('onclick', myFunction);
}
//通过函数名来引用外部函数
funtion myFunction () {
//
}
$(this).addClass("over");
$(this).removeClass("out");
$(this).toggleClass("toggle");
Ajax
jQuery Ajax Features
GET and POST supported
Load JSON,XML,HTML or even scriptsjQuery Ajax特性
获得和发布支持
加载JSON、XML、HTML甚至脚本
var xmlHttp = null;
if (window.XMLHttpRequest) {
// IE7, Mozilla, Safari等浏览器,Use native object.
xmlHttp = new XMLHttpRequest();
} else {
if (window.ActiveXObject) {
// ...其他浏览器,use the ActiveX control for IE5.x and IE6.
xmlHttp = new ActiveXObject('MSXML2.XMLHTTP.3.0');
}
}
$(selector).load():Loads HTML data from the server
$.get() and $.post():Get raw data from the server
$.getJSON():Get/Post and return JSON
$.ajax():Provides core functionality
$(document).ready(function(){
$('#MyButton').click(function(){
$('#MyDiv').load('../HelpDetails.html #SubTOC');
});
});
$('#MyDiv').load('HelpDetails.html #MainToc');
$('#MyDiv').load('../GetCustomers.aspx', {PageSize: 25});
$('#MyDiv').load('NotFound.html',
function (response, status, xhr) {
if (status == "error") {
alert('Error:' + xhr.statusText);
}
});
function (url, params, callback) {
if (typeof url !== "string") {
return this._load(url);
//Don't do a request if no elements are being requested
} else if (!this.length) {
return this;
}
var off = url.indexof(" ");
if (off >= 0) {
var selector = url.slice(off, url.length);
url = url.slice(0, off);
}
//Default to a GET request
var type = "GET";
//If the second parameter was provided
if (params) {
//If it's a function
if (jQuery.isFunction(params)) {
//We assume that it's the callback
callback = params;
params = null;
// Otherwise, build a param string
} else if (typeof params === "object") {
params = jQuery.param(params, jQuery.ajaxSettings.traditional);
type = "POST"
}
}
// Request the remote document
jQuery.ajex({
url: url,
type: type, //GET,POST
data: params,
context: this,
complete: function (res, srarus) {
//etc
}
});
}
get
// example one:
$.get('../HelpDetails.html', function (data) {
$('#MyDiv').html(data);
});
// example two:
$.get('../CustomerJson.aspx', {id: 5 }, function (data) {
alert(data.FirstName);
}, 'json');
function (url, data, callback, datatype) {
//shift arguments if data argument was omited
if (jQuery.isFunction(data)) {
type = type || callback;
callback = data;
data = null;
}
return jQuery.ajax({
type: "GET",
url: url,
data: data,
success: callback,
dataType: type //json,html,xml etc
});
}
getJSON
$.getJSON('../CustomerJson.aspx', {id: 1 }, function (data) {
alert(data.FirstName + '' + data.LastName);
// response.contentType = "application/json";
});
post
$.post('../GetCustomers.aspx', {PageSize: 15 }, function (data) {
$('#MyDiv').html(data.FirstName);
}, 'json');
$.post('../CustomerService.svc/GetCustomers', null, function (data) {
var cust = data.d[0];
alert(cust.FirstName + '' + cust.LastName);
}, 'json');
ajax
$.ajax({
url: '../CustomerService.svc/InsertCustomer',
data: customer,
datatype: 'json',
success: function (data, status, xhr) {
alert("Insert status: " + data.d.Status + '\n' +
data.d.Message);
},
error: frunction (xhr, status, error) {
alert('Error occurred: ' + status);
}
// complete(XMLHttpRequest, textStatus) ..etc
// api.jquery.com/jQuery.ajax/
});
// example two:
$('#MyButton').click(function () {
var customer = 'cust=' +
JSON.stringify({ // src="./json2.js"
FirstName: $('#FirstNameTB').val(),
LastName: $('#LastNameTB').val()
});
$.ajax({
url: '../CustomerService.svc/InsertCustomer',
data: customer,
dataType: 'json',
success: function (data, status, xhr) {
$('#MyDiv').html('Insert status: ' + data.d.Status);
},
error: function (xhr, status, error) {
alert('Error occurred: ' +status);
}
});
});
dom交互
$('div').each(function(index, elem) {
alert(index + '=' + $(elem).text()); //elem = this
});
$('div').each(function(i) {
this.title = "My Index" + i;
$(this).attr('title', 'xxx');
});
var val = $('#CustomerDiv').attr('title');
$('img').attr('title', 'My Image Title');
$('img').attr({
title: '',
style: ''
});
.append(),
.appendTo(),
.prepend(),
.prependTo(),
.remove()
$('.officePhone').append('(office)');
OR
$('(office)').appendTo('.officePhone');
$('.phone').prepend('Phone:');
OR
$('Phone:').prependTo('.phone');
$('.state').wrap('');
Results in:
Arizona
$('.phone, .location').remove();
$('img').css('background-color', 'yellow');
$('img').css({
'background-color': 'yellow',
'width': '10px',
'height': '10px'
});
.addClass(),
.hasClass(),
.removeClass(),
.toggleClass()
$('p').addClass('classOne classTwo');
if($('p).hasClass()) {
//Perform work
}
$('p').removeClass('classOne classTow');
$('p').removeClass();
$('#PhoneDetails').toggleClass('highlight'); //开关
Selectors
var col1 = ${'p, a, span'}; //multipart tags
var col2 = ${'table tr'}; //descendants
alert(col1.length);
$('.BlueDiv, .RedDiv')
$('a.myClass')
or
$('div.BlueDiv, div.RedDiv').css('', '');
alert($('div[title]).length); //[attribute]
or
$('div[title="Div Title"]') //[attrName="attrValue"]
var divs = $('input[type="text"]');
alert(divs.length);
var inputs = $(':input');
alert(inputs[1]); //object
alert($(inputs[1]).val());
example2:
$(':input').each(function () {
var elem = $(this);
alert(elem.val('Foo')); //[object Object]
});
$('div:contains("beautiful")'); //hello beautiful world
$('tr:odd'); //1,3,5,7,9,etc
or
$('tr:even'); //0,2,4,6,8,etc
$('span:first-child');
$('input[value^="Events"]');
or
$('input[value$="Events"]');
$('input[value*="Events"]');
http://codylindley.com/jqueryselectors/
http://api.jquery.com/
入门指南
1.Single File
2.Cross-browser
3.Selectors
4.Events
5.Ajax
6.Plugins
jQuery 1.x //Need to support Id 6-8
jQuery 2.x //Don't need to support IE 6-8
or
')
closest、submit、form(easyui)
$('#MyDiv').change(function() {
$form = $(this).closest('form');
$form.form({
url: '/fileUpload/upload',
ajax:'true',
iframe:'false',
success: function(result) {
result = $.parseJSON(result);
var id = result.obj.id;
}
});
$form.submit(); //submit
});
$('#MyDiv').click(function() {
parent.$.modalDialog({
title: '修改密码',
width: 300,
height: 250,
href: 'user/editUserPwd',
method: 'get',
buttons: [{
text: '保存',
iconCls: 'XXX',
handler: function() {
var form = $.modalDialog.handler.find('#editForm');
form.form('submit');
$.modalDialog.handler.dialog('close');
}
}, {
}]
});
});
$.messager.alert();
$('#myDatagrid').datagrid('reload');
$('#btnSaveItemSeq').linkbutton('disable');
example1:
$("input[type='radio']:checked")
example2:
$("input:radio[name='price']").change(function(
var value = $("input[type='radio']:checked").val();
));
if(null != params) {
var paramArr = params.split(','); //array
}
example1:
Array.prototype.indexOf = function(val) {
var index;
for(index in this) {
if(this[index] == val)
return index;
}
return -1;
}
example2:
var bill = new Employee('Bill Gates', 'Engineer');
Employee.prototype.salary = null;
bill.salary = 20000;
document.write(bill.salary); //20000
var now = new Date().format('yyyy-MM-dd');
function regValidate(val) {
var reg = /^( ([0-9]) | ([1-9][0-9]+) | ([0-9]+/.[0-9]{1,2}) )$/;
var isValidate = reg.test(val);
return isValidate;
}
$('li.third-item').siblings().css('background-color', 'red');
原生js添加监听事件:
$(function() {
if('\v' == 'v') { //true为ie浏览器
document.getElementById('a').attachEvent('onpropertychange', function(e) {
var propertyName = e.propertyName;
alert(propertyName);
);
} else {
document.getElementById('a').addEventListener('onpropertychange', function(e) {
var propertyName = e.propertyName;
alert(propertyName);
});
}
});
使用jquery方法绑定事件:
$(function() {
$('#a').bind('input propertychange', function(e) {
var propertyName = e.propertyName;
alert(propertyName);
});
});
备注:个人博客同步至。