jQuery中$.each()函数的用法引申实例
jQuery中的$.each()函数比forEach更加强大,可以用来遍历JavaScript中的任意集合,借来下来我们会举几个jQuery中$.each()函数的用法引申实例,首先先来回顾一下遍历用法的基础:
$.each( collection, callback(indexInArray, valueOfElement) )
值得一提的是,forEach 可以很方便的遍历数组和 NodeList ,jQuery 中的 jQuery 对象本身已经部署了这类遍历方法,而在原生 JavaScript 中则可以使用 forEach 方法,但是 IE 并不支持,因此我们可以手动把 forEach 方法部署到数组和 NodeList 中:
if ( !Array.prototype.forEach ){
Array.prototype.forEach = function(fn, scope) {
for( var i = 0, len = this.length; i < len; ++i) {
fn.call(scope, this[i], i, this);
}
}
}
// 部署完毕后 IE 也可以使用 forEach 了
document.getElementsByTagName('p').forEach(function(e){
e.className = 'inner';
});
而jQuery中的$.each()函数则更加强大。$.each()函数和$(selector).each()不一样。$.each()函数可以用来遍历任何一个集合,不管是一个JavaScript对象或者是一个数组,如果是一个数组的话,回调函数每次传递一个数组的下标和这个下标所对应的数组的值(这个值也可以在函数体中通过this关键字获取,但是JavaScript通常会把this这个值当作一个对象即使他只是一个简单的字符串或者是一个数字),这个函数返回所遍历的对象,也就是这个函数的第一个参数,注意这里还是原来的那个数组,这是和map的区别。
其中collection代表目标数组,callback代表回调函数(自己定义),回调函数的参数第一个是数组的下标,第二个是数组的元素。当然我们也可以给回调函数只设定一个参数,这个参数一定是下标,而没有参数也是可以的。
jQuery实现html表格动态添加新行的方法
jQuery实现动态添加行的方法
<script src="jquery-1.6.2.min.js"></script>
<script type="text/javascript">
<!-- jQuery Code will go underneath this -->
$(document).ready(function () {
// Code between here will only run when the document is ready
$("a[name=addRow]").click(function() {
// Code between here will only run
//when the a link is clicked and has a name of addRow
$("table#myTable tr:last").after('<tr><td>Row 4</td></tr>');
return false;
});
});
</script>
</head>
<body>
<table id="myTable">
<tr><td>Row 1</td></tr>
<tr><td>Row 2</td></tr>
<tr><td>Row 3</td></tr>
</table>
<a href="#" name="addRow">Add Row</a>
</body>
</html>
还没有评论,来说两句吧...