JQuery - Cheatsheet
文章目录

filter和find的区别

现在有一个页面,里面HTML代码为:

1
2
3
<div>
<p class="rain">测试1</p>
</div>
1
2
3
<div class="rain">
<p>测试2</p>
</div>

如果我们使用 find() 方法:

1
2
var result = $("div").find(".rain");
alert(result.html() ) ;

结果:

1
测试1

如果使用filter()方法:

1
2
var result = $("div").filter(".rain");
alert(result.html());

结果:

1
<p>测试2</p>

结论

  • find() 会在 div 元素内寻找 class 为 rain 的元素,是对它的子集操作
  • filter() 则是筛选 div 的 class 为 rain 的元素,是对它自身集合元素筛选

submit a form in ajax success callback-AJAX成功时回调函数中提交Form

首先 "target": "_blank" 肯定可以打开新页面

重点在于想要添加 async: false

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$.ajax({
url: "...",
method: "post",
data: {
...
},
async: false,
success: function(res) {
form.attr({
"action": newurl,
"target": "_blank"
});
form[0].submit();
}
});

API

1
2
async (default: true)
Type: Boolean

By default, all requests are sent asynchronously (i.e.this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: “jsonp” requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($. Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done().


JQuery-Error: Form submission causing ‘Maximum call stack size exceeded’

Desc

使用 form.submit(); 的时候没有报错但是无限循环执行
过了几秒后报错

1
'Maximum call stack size exceeded'

Solution

http://stackoverflow.com/questions/31379409/form-submission-causing-maximum-call-stack-size-exceeded

Replace $('#fReviewMe').submit(); with:

1
$('#fReviewMe')[0].submit();

calling DOM node method submit to avoid submit jQuery handler ‘loop’.


AJAX相关

AJAX传递额外参数-pass extra arg when ajax finished/succeed

1
2
3
4
5
6
7
8
9
(function(v) {
$.ajax({
url: 'index.cfm?reg_profile'
})
.done(function(data) {
// data
// you can get v here
})
})(btn)

试了几个方法, 比如将参数放到 .done() 里面作为第二个参数等等都不行, 只需要建立一个闭包即可实现

.done() 可以接受三个参数

1
function onMyUrlLoaded(data, textStatus, jqXHR) { /* function code */ };

但是无法通过第四个参数来进行传值

另一种办法:

1
2
3
done(function(magic) {
return process(magic, 42);
});

或者

1
callWithMagic(magic => processMagic(magic, 42));

这样可以传一个42进去


.each()的使用

1
2
3
$('img[id^=CF_HELPTEXT_]').each(function(index, value) {
value.click();
});

将Jquery obj 里面的所有元素都点击一遍


获取数据

substr获得子字符串

1
stringObject.substr(start, length)
参数 描述
start 必需。要抽取的子串的起始下标。必须是数值。如果是负数,那么该参数声明从字符串的尾部开始算起的位置。也就是说,-1 指字符串中最后一个字符,-2 指倒数第二个字符,以此类推。
length 可选。子串中的字符数。必须是数值。如果省略了该参数,那么返回从 stringObject 的开始位置到结尾的字串。

得到选中的option的内容

get the text value of a selected option

1
$("#myselect").val();

If you wanted to get the string “Mr” if the first option was selected (instead of just “1”) you would do that in the following way:

1
2
3
4
5
6
7
8
9
10
< select id = "myselect" >
<
option value = "1" > Mr < /option> <
option value = "2" > Mrs < /option> <
option value = "3" > Ms < /option> <
option value = "4" > Dr < /option> <
option value = "5" > Prof < /option> <
/select>

$("#myselect option:selected").text();

控件相关

select

添加option

1
2
3
4
$('#mySelect').append($('<option>', {
value: 1,
text: 'My option'
}));

If you’re adding options from a collection of items, you can do the following:

1
2
3
4
5
6
$.each(items, function (i, item) {
$('#mySelect').append($('<option>', {
value: item.value,
text : item.text
}));
});

disable select

1
2
$("#" + arrFields[i]).prop('disabled', true);
$("#" + arrFields[i]).prop('disabled', false);

删除select里面所有option

remove all the options of a select box and then add one option and select it

1
2
3
4
5
6
$('#mySelect')
.find('option')
.remove()
.end()
.append('<option value="whatever">text</option>')
.val('whatever');

注意原因不明多个remove()不能一起执行
分成两句后解决问题


Checkbox

Form 提交 checkbox 的特性

  1. 选中才会提交, 不选中连 field 都没有
  2. 默认值是 on, 如果设置 value 可以改变默认值, 但选中一定提交 value, 不选中什么都不提交
  3. 可以考虑多加一个 hidden-input 或者用 JS 动态加一个 field 来实现更复杂的 checkbox

勾选所有Checkbox

1
$('input:checkbox').prop("checked", true);

注意使用的是 prop()

得到checkbox的值

JS 方法

1
document.getElementById('viewDept').checked

Jquery 方法

1
$('id').val()

得到多个值并用逗号分割:

1
2
3
4
5
var state_array = new Array();
$('input[type=checkbox][name=state]:checked').each(function(index, el) {
state_array.push($(this).val());
});
var states = state_array.join(',')

选中某Checkbox的同时取消选择其他所有 jQuery: Uncheck other checkbox on one checked

1
2
3
$('input.chkbox').on('change', function() {
if (this.checked) $('input.chkbox').not(this).prop('checked', false);
});

判断是否被选中

JS:

1
document.getElementById('viewDept').checked

JQuery:

1
$('id').is(':checked')

注意这里使用了伪类


Toggle for editable of inputs

1
2
3
$('#el').prop('disabled', function(i, v) {
return !v;
});
1
$("input[type='checkbox']").is(':checked')

返回结果:选中=true,未选中=false


获取Iframe里面的元素 和 Jquery操作CSS&style

使用Jquery直接获取Iframe里面的元素是不行的
需要多一层操作

1
$("#portalFrameID").contents().find(".smelter-alert").css("background-color", "blue");

表单

获取表单里各种值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
获取值:
文本框, 文本区域: $("#txt").attr("value");
多选框checkbox: $("#checkbox_id").attr("value");
单选组radio: $("input[@type=radio][@checked]").val();
下拉框select: $('#sel').val();

控制表单元素:
文本框, 文本区域: $("#txt").attr("value", ''); //清空内容
$("#txt").attr("value", '11'); //填充内容

多选框checkbox: $("#chk1").attr("checked", ''); //不打勾
$("#chk2").attr("checked", true); //打勾
if ($("#chk1").attr('checked') == undefined) //判断是否已经打勾

单选组radio: $("input[@type=radio]").attr("checked", '2'); //设置value=2的项目为当前选中项
下拉框select: $("#sel").attr("value", '-sel3'); //设置value=-sel3的项目为当前选中项
$("<option value='1'>1111</option><option value='2'>2222</option>").appendTo("#sel") //添加下拉框的option
$("#sel").empty(); //清空下拉框.

JQuery动态添加表单

1
2
3
4
5
6
7
8
9
var $form = $('<form method="post" action="tib.cfm?ajaxModal"></form>');

$form
.append('<input name="index" type="hidden" value="' + $(this).data('metaresultid') + '" />')
.append('<input name="type" type="hidden" value="excel" />')
.appendTo('body')
.submit();

return false;

使用JQuery效率比较高并且兼容性强

获取Jquery对象数组中的所有文字

1
2
3
arr = $('#mw-content-text .navbox-list .navbox-list a').map(function(i, el) {
console.log($(el).text());
}).get();

Jquery对象的属性转为数组 Query select attributes into an array

1
2
3
4
var myVals = [];
$('li', 'ul').each(function() {
myVals.push($(this).attr('value'));
});

页面控制

滚动到对应位置

可以对单个Elem进行滚动,或者对window进行滚动
可以滚动到对应y轴位置,数字作为参数,也可以滚动到对应elem

1
$('#BoxModalContent').scrollTop('#BoxModalContent')

事件

使用 .on() bind事件, 使用 .unBind() 取消bind事件

注意事件不会被覆盖, 因此如果希望加载另一个同名事件则需要先取消加载然后重新bind

1
2
3
$('#modalContinue').unbind('click').on('click', function(event) {
/* do sth*/
});

AJAX 文件上传

注意关于附件,AJAX 仅仅能上传,下载的话需要打开一个新页面。

直接用 form.serialize() 对于文件选择的 input 无效。 因此只需要使用 FormData 这个 Object 即可解决问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$('#upload').on('click', function(event) {

var data = new FormData($("[name=excelUploadForm]")[0]);

$.ajax({
url: 'sir_distExcelUpload.cfm?type=read',
type: 'POST',
cache: false,
contentType: false,
processData: false,
data: data
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});

});

关于attachEvent报错

Error Msg

In IE 11:

Object doesn’t support property or method ‘attachEvent’

In Chrome:

window.attachEvent is not a function

Desc

attachEvent is a deprecated
function used in older versions of Internet Explorer. For modern browsers use this instead.

1
el.addEventListener(evt, func, false);

Solution1

You could also create a function which checks which function to use

1
2
3
4
5
6
7
function addListener(el, event, func) {
if (el.addEventListener) {
el.addEventListener(event, func, false);
} else {
el.attachEvent("on" + event, func);
}
}

Then you can attach your event by doing this:

1
2
3
4
var element = document.getElementById('myElement');
addListener(element, 'click', function() {
alert('You have clicked!');
});

Solution2

If you are unable to do this then perhaps a polyfill will work instead. Try to insert this somewhere:

1
2
3
4
5
if (!document.attachEvent) {
Object.prototype.attachEvent = function(event, func) {
this.addEventListener(event.split('on')[1], func);
}
}

触发实例:

1
$("button#demo").click()

上面的例子将触发 id=”demo” 的 button 元素的 click 事件。

绑定实例:

1
2
3
$("button#demo").click(function() {
$("img").hide()
})
1
2
3
4
$('ul.scopeSelector img.plusminus').click(function() {
//some code
//$(this).next().next().toggle();
});

.trigger()

Desc

Execute all handlers and behaviors attached to the matched elements for the given event type.

Syntax

1
.trigger( event [, extraParameters ] )

实际上就是触发已经有的event

Examples

To pass arbitrary data to an event:

1
2
3
4
5
6
$( "p" )
.click(function( event, a, b ) {
// When a normal click fires, a and b are undefined
// for a trigger like below a refers to "foo" and b refers to "bar"
})
.trigger( "click", [ "foo", "bar" ] );

Alternative way to pass data through an event object:

1
2
3
4
5
$( "body" ).trigger({
type:"logged",
user:"foo",
pass:"bar"
});

.ready()

There is also $(document).on( "ready", handler ) , deprecated as of jQuery 1.8

Desc

Specify a function to execute when the DOM is fully loaded.

Syntax

All three of the following syntaxes are equivalent:

1
2
3
$( document ).ready( handler )
$().ready( handler ) (this is not recommended)
$( handler )

Arguments

  • handler

Type: Function()
A function to execute after the DOM is ready.

Example

The .ready() method is typically used with an anonymous function:

1
2
3
$( document ).ready(function() {
// Handler for .ready() called.
});

Which is equivalent to calling:

1
2
3
$(function() {
// Handler for .ready() called.
});

JQuery&AJAX-Get/Post

示例

1
2
3
4
5
6
<!--请求 test.php 网页,传送2个参数,忽略返回值:
-->
$.get("test.php", {
name: "John",
time: "2pm"
});
1
2
3
4
5
<!--显示 test.php 返回值(HTML 或 XML,取决于返回值):
-->
$.get("test.php", function(data) {
alert("Data Loaded: " + data);
});
1
2
3
4
5
6
7
$(document).ready(function() {
$("#jquery").click(function() {
$.get("result.cfm?name=" + $("#INPUTLOOKUP").val(), function(result) {
$("#result").html(result);
});
});
});

对应的目标处理参考:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$.ajax({
url: "?getdatasubset",
method: "post",
data: {
dids: dids,
cols: columns,
colnames: colnames,
ordr: ordr,
count: count == undefined ? 10 : count
},
success: function(res) {
$('#BoxModalContent').html(res);
},
error: function(xhr, etype, emsg) {
$('#BoxModalContent').html(emsg);
}
});

data中带有多参数的示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$.ajax({
url: "?getdatasubset_XML",
method: "post",
data: {
data: '<data>' + xmlStr + '</data>',
subtitle: subtitle,
showsum: showsum
},
success: function(res) {
$('#BoxModalContent').html(res);
},
error: function(xhr, etype, emsg) {
$('#BoxModalContent').html(emsg);
}
});

定义和用法

get() 方法通过远程 HTTP GET 请求载入信息。
这是一个简单的 GET 请求功能以取代复杂 $.ajax 。请求成功时可调用回调函数。如果需要在出错时执行函数,请使用 $.ajax

参数

Attr Exp
url 必需。规定将请求发送的哪个 URL。
data 可选。规定连同请求发送到服务器的数据。
success 可选。规定当请求成功时运行的函数。

额外的参数:
- success(response, status, xhr)
- response - 包含来自请求的结果数据
- status - 包含请求的状态
- xhr - 包含 XMLHttpRequest 对象
dataType 可选。规定预计的服务器响应的数据类型。默认地,jQuery 将智能判断。
可能的类型:
- “xml”
- “html”
- “text”
- “script”
- “json”
- “jsonp”

页面完全加载完毕后执行

1
2
3
$(window).on('load', function () {
// $('.loading').addClass('animated fadeOut');
});

JQuery-AJAX-Post-Json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var json = {
a: 1,
b: 2
}

var c = 1;
$.ajax({
url: 'getFormFile.cfm',
type: 'POST',
data: {
"a": JSON.stringify(json)
},
success: function(data) {
$('#getDate').html(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error" + errorThrown);
}
})

.bind()

Desc

Attach a handler to an event for the elements.

Syntax

1
$(selector).bind(event,data,function)

其他语法参考官方API:http://api.jquery.com/bind/#bind-events
W3C:http://www.w3school.com.cn/jquery/event_bind.asp

Arguments

  • event

必需。规定添加到元素的一个或多个事件。
由空格分隔多个事件。必须是有效的事件。

  • data

可选。规定传递到函数的额外数据。

  • function

必需。规定当事件发生时运行的函数。

Example

给一个Button绑定点击事件

1
2
3
$("button").bind("click",function(){
$("p").slideToggle();
});

.on()

Syntax

1
$(selector).on( events [, selector ] [, data ], handler )

如果后面的Handler不是一个function变量的话, 就必须写成一个匿名函数

Example

1
2
3
$( "#dataTable tbody tr" ).on( "click", function() {
console.log( $( this ).text() );
});

Pass data to the event handler, which is specified here by name:

1
2
3
4
function myHandler( event ) {
alert( event.data.foo );
}
$( "p" ).on( "click", { foo: "bar" }, myHandler );

Cancel a form submit action and prevent the event from bubbling up by returning false:

1
$( "form" ).on( "submit", false );

Stop submit events from bubbling without preventing form submit, using .stopPropagation().

1
2
3
$( "form" ).on( "submit", function( event ) {
event.stopPropagation();
});

Use the the second argument of .trigger() to pass an array of data to the event handler

1
2
3
4
$( "div" ).on( "click", function( event, salutation, name ) {
alert( salutation + ", " + name );
});
$( "div" ).trigger( "click", [ "Goodbye", "Jim" ] );

.load()

There are 2 .load() function

Categories: Ajax > Shorthand Methods

Syntax

1
.load( url [, data ] [, complete ] )

Description: Load data from the server and place the returned HTML into the matched element.

Args

  • url

Type: String

A string **containing the URL** to which the request is sent.
  • data

Type: PlainObject or String

A plain object or string that is sent to the server with the request.(**The extra data.**)
  • complete

    Type: Type: Function( String responseText, String textStatus, jqXHR jqXHR )

    A callback function that is executed when the request completes.

Callback Function

If a “complete” callback is provided, it is executed after post-processing and HTML insertion has been performed. The callback is fired once for each element in the jQuery collection, and this is set to each DOM element in turn.

1
2
3
$( "#result" ).load( "ajax/test.html", function() {
alert( "Load was performed." );
});

Categories: Events > Document Loading

Deprecated 1.8

Syntax

1
.load( handler )
  • handler

Type: Function( Event eventObject )
A function to execute when the event is triggered.

1
.load( [eventData ], handler )
  • eventData

Type: Anything
An object containing data that will be passed to the event handler.

  • handler

Type: Function( Event eventObject )
A function to execute each time the event is triggered.

Reference

Full API: