如何使用jQuery重写代码

Alg*_*thm 2 javascript jquery

如何使用jQuery重写代码?

 <script type="text/javascript">
    window.onload = function(){
        var array = document.getElementsByTagName('div');
        for (var i=0; i<array.length; i++) {
            (function(i) {
                array[i].onclick = function() {
                    alert(i);
                }
            })(i);
        }
    };
    </script>
    <div>0</div>
    <div>1</div>
Run Code Online (Sandbox Code Playgroud)

谢谢...

use*_*716 5

如果你真的想提醒索引:

示例: http : //jsfiddle.net/Ksyr6/

   // Wrapping your code in an anonymous function that is passed as a parameter
   //    to jQuery will ensure that it will not run until the DOM is ready.
   // This is a shortcut for jQuery's .ready() method
$(function() {
    $('div').each(function( i ) {
         $(this).click(function() {
            alert( i );
         });
     });
});
Run Code Online (Sandbox Code Playgroud)

这会找到所有带有标签 name 的元素'div',并遍历它们,分别分配一个点击事件来提醒其索引。

或者如果索引不重要,它变得更简单:

示例: http : //jsfiddle.net/Ksyr6/1/

$(function() {
    $('div').click(function() {
         // You have access to the element that received the event via "this"
         // alert(this.id) will alert the ID of the element that was clicked
        alert( 'i was clicked' );
     });
});
Run Code Online (Sandbox Code Playgroud)

这里发生了相同的迭代,但它是隐式的。jQuery 遍历'div'元素,在触发警报的单击事件处理程序上提供每个元素。

这是 jQuery 的一个很好的特性。你传递给它一个 CSS 选择器,它找到匹配的元素,并自动迭代它们,触发你调用的任何方法。