【问题标题】:HTML5 Input type time -- which part (hours or minutes) was selected or changed?HTML5 输入类型时间——选择或更改了哪一部分(小时或分钟)?
【发布时间】:2014-08-09 14:26:12
【问题描述】:

在 HTML5 中,输入类型 time 提供了一个输入元素,时间由小时和分钟组成。

当点击hour 部分时,它将被选中,通过点击增量箭头我们可以增加值,分钟也一样...

我们能否知道选择或更改了哪个部分(即小时或分钟)?

【问题讨论】:

  • 发布您的代码。你尝试过的。
  • 您可能希望使用 jquery 来获取您需要的部分。
  • Fork 这个有一些东西可以玩:jsfiddle.net/7G3xS/3
  • 这就是我所看到的。在 jQuery 中设置 .select 处理程序不会产生任何事件。在 jQuery 中设置 .change 处理程序会在小部件第一次完全填充时提供一个事件,如在 01:03 AM 中,然后在此后的每次更改时提供一个更改事件。我没有看到一个字段来指导我确切地改变了什么,但是有很多字段,我没有看透。但是,一些智能编码可以从以前的值中计算出来......

标签: javascript jquery html input


【解决方案1】:

正如上面在 cmets 中 @Paul 所指出的,onselect 事件在这种情况下不起作用。但是,您可以挂钩 change 事件并拆分 HH 和 MM 部分以找出更改了哪一个。

类似的东西:

演示:http://jsfiddle.net/AFdCC/

相关代码:(非常粗略,但会给你的想法)

// handle change event on the element
$("#tm").on("change", function() {
    /*
        cache the default value of the element, 
        this is the value initially applied to the input.
    */
    var before = this.defaultValue;
    var after = this.value;  // current value i.e. changed value
    var partsBefore = before.split(":"); // make an array of old value
    var partsAfter = after.split(":"); // make an array of new value
    if (partsBefore[0] == partsAfter[0]) { // compare old and new value arrays
        if (partsBefore[1] == partsAfter[1]) {
             $("#result").text("Nothing changed"); // this will actually never fire
        } else {
            $("#result").text("Minutes changed");  
        }
    } else {
         $("#result").text("Hours changed");
    }
    this.defaultValue = after; // <-- This is important. 
    /*
        defaultValue holds only the value which was initially applied, 
        so it will always return the initial value. Hence, it is required to
        overwrite it here with the current value so that it could be compared on
        next change.
    */
});

事实上,您也可以将其重构为一个实用函数,您可以在需要时调用它。

【讨论】:

    猜你喜欢
    • 2014-01-16
    • 1970-01-01
    • 2021-03-15
    • 2016-09-12
    • 2011-06-27
    • 1970-01-01
    • 2020-09-08
    • 2021-05-04
    相关资源
    最近更新 更多