【问题标题】:remove disabled attribute for each option in select删除选择中每个选项的禁用属性
【发布时间】:2015-04-20 23:39:36
【问题描述】:

我有一个带有不同选项的选择。我将在过去 30 秒内使用过的选项设置为禁用。我想要得到的是当标准不再有效但页面仍然打开时再次启用选项。 以下代码适用于一个选项,但由于它位于 .each() 内部,因此每个选项都会被覆盖并且它不起作用。 我正在考虑一种解决方法来存储差异值,向元素添加一个类并在具有该类的项目上运行设置超时,但我认为这种代码不是最有效的。 关于如何使用更高效的代码(可能在每个循环内?)获得相同结果的任何想法。

$('#destinatario option').each(function(){
    var ds = $(this).attr('data-ts'); 
    console.log("ts vale "+ds);
    var dateArray = ds.split(" ");  // split the date and time 
    var ds1 = dateArray[0].split("-"); // split each parts in date
    var ds2 = dateArray[1].split(":"); // split each parts in time
    var newDate = new Date(ds1[0], (+ds1[1] - 1), ds1[2], ds2[0], ds2[1], ds2[2]).getTime(); //parse it
    console.log("allora vale "+newDate);
    var currentDate = new Date().getTime();
    console.log("adesso vale "+currentDate);
    var diff = currentDate - newDate;
    console.log(diff);
    if(diff < 30000){
        $(this).prop('disabled', true);
        setTimeout(function() {
            $(this).prop('disabled', false);
        }, (30000-diff));
    }
});

【问题讨论】:

标签: javascript jquery


【解决方案1】:

我遇到了同样的情况,问题是我有一个循环,想为每个循环绑定一个回调以进行更改,我发现所有这些都只适用于最后一个 id,为了解决这个问题,我做了以下绑定调用回调时的参数,以便保存状态:

var arr = ["id1" ,"id2", "id3"];
for(i=0; i<arr.length; i++){
  jQuery("#form_target_input").bind('change',function (id, e){
    yiel.fn.setCookie("form_targeting_"+id, true)
   }.bind(null, id));
 }

你的情况:

setTimeout(function(element, e) {
   $(element).prop('disabled', false);
}.bind(null, this), (30000-diff));

【讨论】:

  • 我不喜欢使用 .bind 我解决了将设置超时移到每个函数之外(实际上它与您的代码相同)。
  • 是的,它做同样的伎俩这里的想法是知道为什么会发生这种情况,发现问题是解决问题的难点有很多方法。
  • 在这种情况下:每个都是一个循环,因此每次都会覆盖 setTimeout。绑定重复 setTimeout 和瞧!
【解决方案2】:

尝试更改最后一部分:

setTimeout(function() {
    $(this).prop('disabled', false);
}.bind(this), (30000-diff));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    相关资源
    最近更新 更多