Jquery专注于输入字段 [英] Jquery Focus on input field

查看:119
本文介绍了Jquery专注于输入字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

页面上的HTML有20个< input> 字段,每个字段的命名和给定ID的顺序从1到20递增。

The HTML on the page has 20 <input> fields each named and given ID's in increasing order from 1 to 20.

如果变量 id 设置为下一个连续 id id + 1),此函数将使焦点应用于该字段。但是,当在当前输入字段外部单击时,如果输入的数字大于10,则最后一个输入字段将不会重新获得焦点,但会显示警告。

If the variable id is set to the next sequential id (id + 1), this function will cause focus to apply to that field. However, when clicking outside of the current input field, the last one input field will not regain focus if the number entered is greater than 10, but an alert will be displayed.

$(":input").focusout(function(){
    var input = $(this).val();
    var id    = $(this).attr('id');
    if(input > 10){ 
        alert('You must enter a number between 0 and 10 '+id);
        $("#"+id).select();
    }
});

如何设置最后一个输入字段以重新获得焦点?

How can the last input field be set to regain focus?

推荐答案

尝试替换:

$("#"+id).select();

使用:

$(this).focus();

在这种情况下, $(#+ id) $(this)是相同的元素,我假设您想要焦点有错误的元素。

In this case, $("#"+id) and $(this) are the same element, and I'm assuming you want to focus the element when there is an error.

除此之外:我不相信 id name 值可以合法地从一个数字开始,你可能想要用 option1 option2 等。它可能有用,但它也可能导致以后难以调试的问题。最好在谨慎和最佳实践方面犯错误。

Aside: I don't believe that id or name values can legally start with a number, you may want to prefix them with something like option1, option2, etc. It might work, but it might also cause issues later that are difficult to debug. Best to err on the side of caution and best practices.

HTML中id属性的有效值是什么?

编辑:无法获得 focus()工作后,我尝试使用 setTimeout 并且能够制作它发生。我不确定为什么,或者这是否真的有必要,但似乎有效。

Edit: After failing to get focus() to work, I tried with setTimeout and was able to make it happen. I'm not sure why, or if this is really necessary, but it seems to work.

$(":input").focusout(function(){
    var $this = $(this),
        input = $this.val();

    if (input > 10){
        alert('You must enter a number between 0 and 10');
        setTimeout(function(){
        $this.focus();
        }, 1); 
    }
}); 

我很想知道是否有更好的方法可以做到这一点或解释。我怀疑模糊和焦点事件是不是按照使前一个方法成为可能的顺序触发的?

I'd love to hear if there is a better way to do this or an explanation. I suspect that the blur and focus events are not fired in an order that makes the previous method possible?

演示: http://jsfiddle.net/zRWV4/1/

如评论中所述,你应该最终确保该值是一个整数 parseInt 或类似的(你似乎已经意识到这一点)。

As mentioned in the comments, you should eventually make sure the value is an integer with parseInt or similar (you seem to already be aware of this).

这篇关于Jquery专注于输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆