Javascript焦点使用.focus()

时间:2013-12-02 02:51:29

标签: javascript jquery

如果time_start>我有关于javascript的问题。 24 java脚本警报显示然后将焦点或autofocs放在该文本框上。但重点不起作用我不知道为什么这是一个小问题,但请检查一下。

的javascript

 function start_time(){

   var time_start = document.getElementById("start_t").value;
    if(time_start > 24){
        alert("Invalid Start time hours");
         document.getElementById('start_t').focus();
  } 
 }

HTML

 <input type="text" size="2" value="00" name="start" id="start_t" style="text-align: center;" onchange="start_time()">:

我想做的是在值无效时自动关注该文本框

2 个答案:

答案 0 :(得分:3)

您的值是字符串,您正在比较整数。您需要解析该值并将其转换为整数。

变化:

var time_start = document.getElementById("start_t").value;

要:

var time_start = parseInt(document.getElementById("start_t").value, 10);

如果你正在使用jQuery,就像你的标签建议你应该这样做。

var time_start = parseInt($('#start_t').val(), 10);

此外,如果你使用jQuery,你可以将焦点设置为这样的元素:

$('#start_t').focus();

尝试将警报切换到确认对话框,以便获得返回值,然后设置焦点。

请更改此内容:

if (time_start > 24) {
    alert("Invalid Start time hours");
    document.getElementById('start_t').focus();
}

对此:

if (time_start > 24) {
    var r = confirm("Invalid Start time hours");

    if (r) {
        $('#start_t').focus();
    }  
}

看看这个小提琴:http://jsfiddle.net/sm4Nk/

答案 1 :(得分:1)

我知道一个有效的解决方案,但没有正当理由。您的代码有两个问题

  1. 将String与整数进行比较

    function start_time(){
        var time_start = document.getElementById("start_t").value; 
        // time_start is a string. convert it into Integer first
        if(time_start > 24){ // you are comparing integer with string
            alert("Invalid Start time hours");
            document.getElementById('start_t').focus();
      } 
    }
    

    您需要更改此功能,如下所示

    function start_time(){
         var time_start = parseInt(document.getElementById("start_t").value;
         if(isNaN(time_start) || time_start > 24){ 
             alert("Invalid Start time hours");
             document.getElementById('start_t').focus();
         }             
    }
    
  2. 专注于change事件。对于input type='text'更改事件会因模糊而触发。每当我在'change'事件上使用JavaScript将焦点放在焦点上时,我就遇到了问题。见fiddle。为了克服这个问题,有两种解决方案,

    一个。要么在点击按钮时执行您正在执行的操作,请参阅fiddle

    湾或者在超时后进行焦点fiddle

    setTimeout( function() { document.getElementById('start_t').focus()} ,1);
    
  3. PS:请注意我在小提琴中使用jQuery,我在使用本机JavaScript函数时有点懒惰