2012-03-14 65 views
0

我有我的這些形式的按鈕,我想結合「的mouseenter」和「鼠標離開」事件,他們這是我寫Jquery-。每()不工作

$("button").each(function() { 
    $(this).bind("mouseenter", function() { $(this).css("border", "1px gray outset") }); 
    $(this).bind("mouseleave", function() { $(this).css("border", "none") }); 
}); 

這個代碼代碼只能在第一個按鈕上工作,其餘的事情都不會發生。 這是我的全碼:

$("button").each(function() { 
$(this).hover(function() { $(this).css("border", "1px gray outset") }, function() { $(this).css("border", "none") }); 
    $(this).bind("mousedown",$(this).css("border", "inset")); 
    $(this).click(DoSubmit($(this), 'CLICK', '')); 
    }); 
+1

沒有什麼錯,你發佈的代碼(http://jsfiddle.net/xJ6Ff/)。嘗試在http://jsfiddle.net上設置演示,以顯示您遇到的問題。 – Matt 2012-03-14 10:29:55

+0

[Works for me。](http://jsbin.com/uxiziq)(在Firefox上)。 – kennytm 2012-03-14 10:30:44

+0

這個腳本是否包含在第一個按鈕之後,但在其他按鈕之前?或者你在執行這個函數後用Ajax加載其他按鈕?這個代碼本身沒有任何問題。 – 2012-03-14 10:34:41

回答

2

直接寫:

$("button").mouseenter(function(){ $(this).css("border", "1px gray outset");}).mouseleave(function(){ $(this).css("border", "none");}); 

JS小提琴演示:http://jsfiddle.net/tkSdW/

+0

這相當於他使用的代碼......它不會*修復*任何東西。 – Matt 2012-03-14 10:31:18

+0

@RoryMcCrossan:道歉,如果我失去了一些東西,但[沒有問題](http://jsfiddle.net/xJ6Ff) – Matt 2012-03-14 10:35:28

+1

@Rory:代碼*是*等效。 OP的原始代碼起作用(如Matt所示)。所以如果它不適用於OP,這也不應該。這並不意味着它不應該這樣寫(它應該),但它不會解決OP的問題(*如果有問題*)。國際海事組織,我們必須等到(S)他澄清... – 2012-03-14 10:36:43

1

沒有必要在each()循環分配事件處理程序。單單選擇將返回元素的數組,然後jQuery將事件應用到這些元素:

$(function() { 
    $("button").bind("mouseenter", function() { $(this).css("border", "1px gray outset") }); 
    $("button").bind("mouseleave", function() { $(this).css("border", "none") }); 
}); 

Example fiddle

2

沒有錯,你的代碼

提供它後運行DOM已加載,這意味着內部

$(function(){ 
    $('button')... 
}); 

此外,您不必每次使用,如果你只使用迭代事件綁定到當前元素..

您可以

$("button") 
    .bind("mouseenter", function() { $(this).css("border", "1px gray outset") }) 
    .bind("mouseleave", function() { $(this).css("border", "none") }); 
1

雖然直接綁定到整個集團的原代碼is working just fine,因爲它是,我會建議使用.hover()方法這是做同樣的事情,但用更少的代碼:

$("button").hover(function() { 
    $(this).css("border", "1px gray outset"); 
}, function() { 
    $(this).css("border", "none"); 
}); 

Live test case

1

你可能想這

$("button").each(function(index,value) { 
    $(value).bind("mouseenter", function() { $(value).css("border", "1px gray outset"); }); 
    $(value).bind("mouseleave", function() { $(value).css("border", "none"); }); 
});