<!-- HTML结构 -->
<ul class="lang">
<li class="js dy">JavaScript</li>
<li class="dy">Python</li>
<li id="swift">Swift</li>
<li class="dy">Scheme</li>
<li name="haskell">Haskell</li>
</ul>
find()查找
var ul = $('ul.lang'); // 获得<ul>
var dy = ul.find('.dy'); // 获得JavaScript, Python, Scheme
var swf = ul.find('#swift'); // 获得Swift
var hsk = ul.find('[name=haskell]'); // 获得Haskell
parent()方法
var swf = $('#swift'); // 获得Swift
var parent = swf.parent(); // 获得Swift的上层节点<ul>
var a = swf.parent('div.red'); // 从Swift的父节点开始向上查找,直到找到某个符合条件的节点并返回
next()和prev()方法
var swift = $('#swift');
swift.next(); // Scheme
swift.next('[name=haskell]'); // Haskell,因为Haskell是后续第一个符合选择器条件的节点
swift.prev(); // Python
swift.prev('.js'); // JavaScript,因为JavaScript是往前第一个符合选择器条件的节点
过滤
filter()方法
var langs = $('ul.lang li'); // 拿到JavaScript, Python, Swift, Scheme和Haskell
var a = langs.filter('.dy'); // 拿到JavaScript, Python, Scheme
var langs = $('ul.lang li'); // 拿到JavaScript, Python, Swift, Scheme和Haskell
langs.filter(function () {
return this.innerHTML.indexOf('S') === 0; // 返回S开头的节点
}); // 拿到Swift, Scheme
map()方法把一个jQuery对象包含的若干DOM节点转化为其他对象
var langs = $('ul.lang li'); // 拿到JavaScript, Python, Swift, Scheme和Haskell
var arr = langs.map(function () {
return this.innerHTML;
}).get(); // 用get()拿到包含string的Array:['JavaScript', 'Python', 'Swift', 'Scheme', 'Haskell']
first()、last()和slice()方法
var langs = $('ul.lang li'); // 拿到JavaScript, Python, Swift, Scheme和Haskell
var js = langs.first(); // JavaScript,相当于$('ul.lang li:first-child')
var haskell = langs.last(); // Haskell, 相当于$('ul.lang li:last-child')
var sub = langs.slice(2, 4); // Swift, Scheme, 参数和数组的slice()方法一致
练习
<form id="test-form" action="#0" onsubmit="doClick()">
<p><label>Name: <input name="name"></label></p>
<p><label>Email: <input name="email"></label></p>
<p><label>Password: <input name="password" type="password"></label></p>
<p>Gender: <label><input name="gender" type="radio" value="m" checked> Male</label> <label><input name="gender" type="radio" value="f"> Female</label></p>
<p><label>City: <select name="city">
<option value="BJ" selected>Beijing</option>
<option value="SH">Shanghai</option>
<option value="CD">Chengdu</option>
<option value="XM">Xiamen</option>
</select></label></p>
<p><button type="submit">Submit</button></p>
</form>
<script>
'use strict';
function doClick() {
'use strict';
var json = null;
var resultMap = {};
$('#test-form :input:not(button)').map(function() {
if(this.name == "gender") {
resultMap[this.name] = $('input[type=radio]:checked').val();
} else {
resultMap[this.name] = this.value;
}
});
json = JSON.stringify(resultMap);
// 显示结果:
if(typeof(json) === 'string') {
alert(json);
} else {
alert('json变量不是string!');
}
}
</script>