如何使用 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>
谢谢...
最佳答案
如果您确实想提醒索引:
示例: 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 );
});
});
});
这会找到所有带有标签名称 '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' );
});
});
这里发生相同的迭代,但它是隐式的。 jQuery 迭代 'div'
元素,为每个元素提供触发警报的单击事件处理程序。
这是 jQuery 的一个很好的功能。你向它传递一个 CSS 选择器,它会找到匹配的元素,并自动迭代它们,触发你调用的任何方法。
关于javascript - 如何使用 jQuery 重写代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3793995/