[英]How to rewrite the code using 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>
谢谢...
如果您确实想提醒索引:
示例: 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'
所有元素,并对其进行迭代,并分别分配警告其索引的click事件。
或者,如果索引不重要,它将变得更简单:
示例: 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'
元素,为每个单击事件处理程序提供触发警报'div'
元素。
这是jQuery的一个不错的功能。 您将其传递给CSS选择器,它会找到匹配的元素,并自动迭代它们,触发您调用的任何方法。
我不会为您重写它,但会提供一些提示:
document.getElementsByTagName
等效的是jQuery
函数(通常别名为$
除非您使用noConflict
)。 jQuery的版本实际上接受CSS3的所有选择器(然后是某些)。 window.onload
是load
事件window
,您可以通过挂钩.load
,但你可能想看看jQuery.ready
一个更好的选择。 .click
函数绑定click
处理程序。 .each
上述#1结果中的所有匹配元素。 花几个小时阅读jQuery API文档是非常值得的。 (大概)还有大约157,342本书(显然,阅读时间会更长)。 ;-)从长远来看,即使您一开始似乎会放慢速度,阅读该书也可以节省很多时间。 玩得开心!
jQuery(function(){
jQuery('div').bind('click',function(){
alert('alert');
})
});
。
$(function(){
$('div').each(function(i){
$(this).click(function(){
alert(i);
})
});
});
jQuery('document').ready(function(){ jQuery('div').click(function(){ alert(jQuery(this).html()); }); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.