2009-10-13 18 views
2

我是jQuery的新手,我試圖在沒有選擇任何輸入的情況下觸發keyPress上的函數。我在測試焦點時遇到問題。以下是我目前擁有的功能,但它無法正常工作。有什麼建議?如果沒有選擇輸入,在按鍵上觸發一個函數

var inputHasFocus = false; 
$('#myForm :input').each(is(":focus")){ 
    inputHasFocus = true; 
}; 

if (inputHasFocus == false){ 

    $("*").keypress(function (e) { 
     // the function 
    }); 
} 

回答

2
var focusedInputs = $("#myForm input:focus"); 
if (focusedInputs != null && focusedInputs.length > 0) { inputHasFocus = true; } 

類似的東西。

+0

感謝計劃B一旦我把它放在按鍵內工作得很好。看起來其他響應也會起作用,但我首先嚐試了這一方法,但它的工作原理讓我沒有嘗試其他方法。感謝你們倆! 。 $( 「*」)按鍵(功能(E){ \t VAR inputHasFocus = FALSE; \t VAR focusedInputs = $( 「#myForm的輸入:焦點」); \t如果(focusedInputs = NULL && focusedInputs!長度> 0){ \t inputHasFocus = TRUE;}! \t如果(inputHasFocus =真){ \t \t //的每一個鍵被按下,沒有選擇的輸入時間運行該函數 \t} \t} }) ; – Lance 2009-10-13 19:13:26

+0

我很高興它爲你工作! :) – 2009-10-13 19:20:33

1

如下我會嘗試一下:

var inputHasFocus = false; 

$('#myForm :input').focus(function() { 
    inputHasFocus = true; // Set true if a Form-Field is selected 
}).blur(function() { 
    inputHasFocus = false; // Set false if a Form-Field has left 
}); 

$("*").keypress(function() { 
    if(!inputHasFocus) { 
     // check if(inputHasFocus) after the keypress has done 
     // otherwise you have the basic value in the var inputHasFocus 
     // here you can run your function... 
    } 
}); 

jQuery的文檔,鏈接所使用的功能:

0

你也可以嘗試這樣的:

var inputHasFocus = false; 

$('#myForm input').each(function() { 

if ($(this).is(":focus")) { 
    inputHasFocus = true; 
} 

}; 
+0

幾乎完全是什麼snuffer.ch建議除了沒有模糊。 – ohaal 2012-10-20 01:26:43