2013-04-23 88 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(''); 
     } 
    } 
});