jQuery学习笔记

2018-12-06  本文已影响0人  许俊贤

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);
});
});

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

上一篇 下一篇

猜你喜欢

热点阅读