2014-04-27 32 views
1

我想为114 div应用鼠标事件。有一个div有很多条件。我写了一个div,但大约有900行。如果我想为114 div做这件事,这将是非常困难和无聊。我尝试了下面的例子,但没有奏效。在鼠标事件中使用数组

var abc= new Array(); 
abc[0] = ".ABC"; 
abc[1] = ".DEF"; 

$(abc).mouseenter(function() { 
    Some code 
}); 

for (var a=0;a<114;a++) { 
    $(abc[a]).mouseenter(function() { 
     Some code 
    }); 
} 

while (var a=0;a<114;a++) { 
    $(abc[a]).mouseenter(function() { 
     Some code 
    }); 
} 

回答

1

没有必要通过一个定义每一个事件。所有div的给类和类名选择:

jsFiddle Demo

HTML

<div class="mydivs"></div> 
<div class="mydivs"></div> 
<div class="mydivs"></div> 
.... 

jQuery的

$('.mydivs').mouseenter(function() { 
    // grab current div by $(this) 
}); 
+0

你确定你要定义114倍,而不是总是指同一 –

+0

同样的功能@ Siamak.AM哦。我一整天都在工作。我想不出来。 :) 谢谢。 – Zeki

0

更好的解决方案可能是只放所有你想要相同的事件处理程序的元素上的普通类,或者(如果你向我们展示你的HTML),哟你也许可以使用一个委托事件处理程序。但是,如果你坚持在阵列中设立单独的事件处理程序的每一个项目,你可以这样做:

$(abc.join(", ")).mouseenter(function() { 
    // you can access whatever object triggered the event 
    // with the value in this 
});