2013-04-23 92 views
0

我的網頁上有一個HTML計算器。我想要做的是選擇一個input字段,然後通過單擊編號爲div的元素輸入值,但是當我點擊input和之後的div時,重點是div。我如何使用jQuery來防止這種情況。防止所選元素的焦點

HTML calculator

在下面fiddle你會看到,當我點擊輸入元素,並嘗試輸入值,重點將離開!我怎樣才能解決這個問題,並在輸入字段中記錄相關的值?

+1

如果你避免這種情況的點擊不會在您需要的DIV被獲取,而在div點擊返回處理焦點輸入。 – slash197 2013-04-23 06:19:07

+1

你最好用一些代碼而不是截圖來製作一個jsFiddle簡單的例子。 – 2013-04-23 06:19:58

+0

重點應該來還是不應該來輸入字段? – 2013-04-23 06:21:31

回答

0

定義準備對文檔的變量

var focusedInput;

如果焦點更改到任何輸入商店輸入focusedInput

focusedInput = $(this);

上的div點擊編寫代碼

$('div.num-button').click(function(){

//some code here

$(focusedInput).focus(); //handle null exception

});

0

我知道這是非常晚,但是,如果其他人來尋找這個答案可能會有所幫助。

正如@anil所說,創建一個變量,您可以在其中存儲您關注的輸入。然後,當你專注於你的輸入時,將元素存儲在變量中。現在當您點擊您的「鍵盤」時,獲取該值並將其添加到焦點變量輸入值。

這裏是my fiddle,我從你原來的小提琴分支。

這是代碼:

var focused; 
// Stored the input 
$('input').focus(function() { 
    focused = $(this); 
}); 

// Listen for clicks on the number button 
$('.num-button').click(function(){ 
    // Get the value of the number button that was clicked as string 
    var intVal = $(this).find('span').text().toString(); 
    // Make sure that we have a focused input 
    if(typeof focused != 'null' || typeof focused != 'undefined') { 
     // Only add numbers to the input field 
     if(intVal != "DONE" && intVal != "Del") { 
      // Get the values as strings 
      var curVal = focused.val().toString(), 
       newVal = curVal + intVal; 
      focused.val(newVal); 
     } else if (intVal == "Del") { 
      // Clear the value if the Del "key" was clicked. 
      focused.val(''); 
     } 
    } 
});