jQuery学习笔记

jQuery

部分函数

<!-- toggle事件点击轮番触发-->
$('#MyTable tr').toggle(
  function () {
    $(this).css('background-color', '#efefef');
  },
  function () {
    $(this).css('background-color', '#efefef');
  }
  function () {
    $(this).css('background-color', 'Yellow');
  }
);

<!--hover事件,相当mouseEnter & mouseLeave -->
<!-- 集成写法-->
$('#myTable tr').hover(
  $(this).toggleClass('LightHighlight');
);
<!--分开写法-->
$('#myTable tr').hover(
  function () {
    //mousenter
    $(this).css('background-color', '#efefef');
  },
  function () {
    //mouseleave
    $(this).css('background-color', '#fff');
  }
);

<!--ready方法与on事件 -->
$(document).ready(
  function () {
    var tbody = $('#myTable tbody');
    <!-- tbody下所有td绑定click事件 -->
    tbody.on('click', 'td', function(){
      alert($(this).text());
    });
  }
);

<!--jquery ,find()方法-->
var table = $('#myTable");
//var tbody = table.find('tbody');
table.find('tbody').on('click', function () {
//
});

<!-- on事件,绑定多个事件 -->
$(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);
    }
  });
});
<!--写法二:多事件与操作写成map形式  -->
$('tr').on({
  click: function () {
  },
  mouseenter: function () {
  },
  mouseleave: function () {
  },
  <!-- 鼠标点击事件 -->
  mouseup: function (e) {
  }
});

<!-- 事件非绑定写法 -->
$("#myDiv").mounseenter(function () {
//
})
.mouseleave(function () {
//
})
.mouseup(funtion (e) {
//
});

<!-- change事件 -->
$('.MyInput').change(function () {
  alert($(this).val());
  $(this).addClass('Highlight');
});

<!-- dom, addEventListener及attachEvent属性值及其方法 -->
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 () {
//
}

<!-- 有关Class的方法 -->
$(this).addClass("over");
$(this).removeClass("out");
$(this).toggleClass("toggle");

Ajax

jQuery Ajax Features
GET and POST supported
Load JSON,XML,HTML or even scripts

jQuery Ajax特性
获得和发布支持
加载JSON、XML、HTML甚至脚本

<!-- 与Ajax相关的 XMLHTTP -->
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');
  }
}

<!--jQuery Ajax Functions -->
$(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

<!-- Loading HTML Content from the Server -->
<!-- $(selector).load(url,data,callback) -->
$(document).ready(function(){
  $('#MyButton').click(function(){
    $('#MyDiv').load('../HelpDetails.html #SubTOC');
  });
});
<!-- 过滤页面信息 -->
$('#MyDiv').load('HelpDetails.html #MainToc');

<!-- passed data to the server -->
$('#MyDiv').load('../GetCustomers.aspx', {PageSize: 25});

<!-- 返回callback -->
$('#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

<!-- $.get(url, date, callback, datatype) -->
// 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(url, data, callback) -->
$.getJSON('../CustomerJson.aspx', {id: 1 }, function (data) {
alert(data.FirstName + '' + data.LastName);
// response.contentType = "application/json";
});

post

<!-- $.post(url, data, callback, datatype) -->
$.post('../GetCustomers.aspx', {PageSize: 15 }, function (data) {
$('#MyDiv').html(data.FirstName);
}, 'json');

<!-- to Call a WCF Service -->
$.post('../CustomerService.svc/GetCustomers', null, function (data) {
var cust = data.d[0];
alert(cust.FirstName + '' + cust.LastName);
}, 'json');

ajax

<!--
Configure using JSON properties:
1. contentType
2. data
3. dataType
4. error
5. success
6. type (GET or POST)
-->
$.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);
}
});
});
<!-- request headers: GET /CustomerService.svc/InsertCustomer?cust={"FirstName":"John","LastName":"Doe"} HTTP/1.1 -->

dom交互

<!-- Iterating Through Nodes -->
$('div').each(function(index, elem) {
alert(index + '=' + $(elem).text()); //elem = this
});

<!-- this.propertyName -->
$('div').each(function(i) {
this.title = "My Index" + i;
$(this).attr('title', 'xxx');
});

<!-- attr() -->
var val = $('#CustomerDiv').attr('title');
<!-- modifying Attributes -->
$('img').attr('title', 'My Image Title');
<!-- Multiple Attr -->
$('img').attr({
title: '',
style: ''
});


<!-- Adding and Removing Nodes -->
.append(), 
.appendTo(),
.prepend(),
.prependTo(),
.remove()
<!-- Appending to Nodes -->
$('.officePhone').append('<span>(office)</span>');
OR
$('<span>(office)</span>').appendTo('.officePhone');
<!-- Prepending to Nodes -->
$('.phone').prepend('<span>Phone:</span>');
OR
$('<span>Phone:</span>').prependTo('.phone');

<!-- Wrapping Elements -->
$('.state').wrap('<div class="US_State" />');
Results in:
<div class="US_State">
<div class="state">Arizona</div>
</div>

<!-- .remove() -->
$('.phone, .location').remove();


<!-- Modifying Styles -->
$('img').css('background-color', 'yellow');
<!-- Multiple Styles -->
$('img').css({
'background-color': 'yellow',
'width': '10px',
'height': '10px'
});

<!-- Modifying CSS Classes -->
.addClass(),
.hasClass(),
.removeClass(),
.toggleClass()
<!-- Adding a CSS Classes -->
$('p').addClass('classOne classTwo');
<!-- Matching CSS Classes -->
if($('p).hasClass()) {
//Perform work
}
<!-- Removing CSS Classes -->
$('p').removeClass('classOne classTow');
<!-- Remove all class -->
$('p').removeClass();
<!-- Toggling CSS Classes -->
$('#PhoneDetails').toggleClass('highlight'); //开关

Selectors

<!--Selectors -->
var col1 = ${'p, a, span'}; //multipart tags 
var col2 = ${'table tr'}; //descendants
alert(col1.length);

<!-- Multiple Class Name -->
$('.BlueDiv, .RedDiv')
<!-- Selecting by Tag Name and Class Name -->
$('a.myClass')
or
$('div.BlueDiv, div.RedDiv').css('', '');

<!-- Selecting By Attr Value -->
alert($('div[title]).length); //[attribute]
or 
$('div[title="Div Title"]') //[attrName="attrValue"]

<!-- Input tag name -->
var divs = $('input[type="text"]');
alert(divs.length);
<!-- all Input Elements:input, select, textarea,
button, image, radio and more -->
var inputs = $(':input');
alert(inputs[1]); //object
alert($(inputs[1]).val());
example2:
$(':input').each(function () {
var elem = $(this);
alert(elem.val('Foo')); //[object Object]
});

<!-- Additional Selector Features -->
<!-- Using Contains in Selectors -->
$('div:contains("beautiful")'); //<div>hello beautiful world</div>

<!-- Using Even or Odd Rows in a Table -->
$('tr:odd'); //1,3,5,7,9,etc
or
$('tr:even'); //0,2,4,6,8,etc

<!-- selects the first child of every element group
<div>
<span>First Child,first group</span>
<span>XXX</span>
</div>
<div>
<span>First Child,second group</span>
<span>XXX</span>
</div>
-->
$('span:first-child');

<!-- Using 'Starts' or 'Ends' With in Selectors
<input type="button" value="Events-World"/> //value^="Events"
<input type="button" value="Events-World"/>
<input type="button" value="World Events"/> //value$="Events"
<input type="button" value="National Events"/>
-->
$('input[value^="Events"]');
or
$('input[value$="Events"]');

<!-- Find Attr Containing a Value 
<input type="button" value="World Events 2011"/> //value*="Events"
<input type="button" value="National Events 2011"/>
-->
$('input[value*="Events"]');

<!-- jQuery Selectors -->
http://codylindley.com/jqueryselectors/
<!-- jQuery API Documentation -->
http://api.jquery.com/

入门指南

<!-- Getting Started with jQuery -->
1.Single File 
2.Cross-browser
3.Selectors
4.Events
5.Ajax
6.Plugins

<!-- jQuery script
<head>
<script type="text/javascript" src="jquery.js"></script>
</head>
-->
jQuery 1.x //Need to support Id 6-8
jQuery 2.x //Don't need to support IE 6-8

<!-- Using a Content Delivery Network(CDN) -->
<script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jquery/jquery-[version].js"></script>
or
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/[version]/jquery.min.js"></script> 
<!-- load the script locally -->
<script>
window.jQuery || document.write('<script src="jquery.js"></script>')
</script>

<!-- $(document).ready()
1.detect when a page has loaded and is ready to use
2.Called once DOM hierarchy is loaded(but before all images have loaded)
-->
<script type="text/javascript">
$(document).ready(function() {
alert('DOM loaded'); //First
});
window. function() {
alert('Window loaded'); //Final
};
</script>

closest、submit、form(easyui)
<!-- closest() && submit() &&
form(options) -- jquery.easyui.min.js 
-->
$('#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
});


<!-- parent.$.modalDialog(options) -->
<!-- parent: Window
$: f m(a,b) jquery对象: jquery.min.js
modalDialog(options): f anonymous(options): extJs.js
handler: m.fn.init(1) jquery对象 
form(): easyui方法:jquery.easyui.min.js
dialog('close'): easyui方法:jquery.easyui.min.js
-->
$('#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');
}
}, {

}]
});
});

<!-- $: f m(a,b) jquery对象: jquery.min.js
messager: Object对象 easyui.js
alert(): easyui方法 easyui.js
--> 
$.messager.alert();


<!-- datagrid('reload') : easyui方法 
linkbutton('disable') : easyui方法 
-->
$('#myDatagrid').datagrid('reload');
$('#btnSaveItemSeq').linkbutton('disable');


<!-- 
<input name="price" type="radio" checked="checked" /> 
<input name="price" type="radio"/> 
-->

example1:

$("input[type='radio']:checked")

example2:

$("input:radio[name='price']").change(function(
var value = $("input[type='radio']:checked").val(); 
));

<!-- split() -->
if(null != params) {
var paramArr = params.split(','); //array
}

<!-- prototype: define method or attribute --> 
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

<!-- format() -->
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;
}


<!-- siblings(): 同层级下其他标签 -->
$('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);
});
});

备注:个人博客同步至简书。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,542评论 6 504
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,822评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,912评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,449评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,500评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,370评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,193评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,074评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,505评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,722评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,841评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,569评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,168评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,783评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,918评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,962评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,781评论 2 354

推荐阅读更多精彩内容