看起來你正在使用數字作爲標識,這裏是介紹如何創建的ID在計算器上一個偉大的答案:What are valid values for the id attribute in HTML?。
$(document).ready(function()
{
for(var i = 1; i < 8; i++)//see that I removed the $ preceeding the `for` keyword, it should not have been there
{
$("#"+i).hover(function() {
$(this).stop().animate({left:"50px"});//also notice that instead of using `"#" + i` as the selector inside the anonymous function I changed it to `this` so it properly references the hovered element
},
function() {
$(this).stop().animate({left:"30px"});
});
}
});
如果你添加一個類你都綁定到這個元素可以majorly簡化:
$(function()
{
$(".hover-class").hover(function() {
$(this).stop().animate({left:"50px"});
},
function() {
$(this).stop().animate({left:"30px"});
});
});
下面是該解決方案的演示:http://jsfiddle.net/FJQNa/
這將選擇所有具有hover-class
類的元素,並將事件處理程序綁定到它們。
編輯
您還可以通過用逗號分隔的選擇器選擇一次使用ID的多個元素:jQuery的
$(function()
{
$("#ele-1, #ele-2, #ele-3, #ele-4, #ele-5, #ele-6, #ele-7").hover(function() {
$(this).stop().animate({left:"50px"});
},
function() {
$(this).stop().animate({left:"30px"});
});
});
文檔的多個選擇:http://api.jquery.com/multiple-selector/
請[格式化你的問題和代碼(http://stackoverflow.com/editing-help),以便其他人可以閱讀。 – 2011-12-15 18:08:27
這可以用CSS來完成。不需要jQuery ... – 2011-12-15 18:11:20
1)你是否使用數字ID? 2)對於標記有$ - 應該是一個錯誤。 – Anthony 2011-12-15 18:11:40