【问题标题】:HTML input value disappears after adding jquery datepicker option?添加 jquery datepicker 选项后 HTML 输入值消失?
【发布时间】:2016-07-28 12:42:37
【问题描述】:

我有多个这样的文本输入:

<input type="text" class="datepicker" value="11-11-2016">

还有 jquery 脚本:

  $(".datepicker").each(function() {
    $(this).datepicker();
    $(this).datepicker("option", "changeYear", true);
  });

页面加载后输入值立即消失!!!

如果我删除该选项:

$(this).datepicker("option", "changeYear", true);

...该值不会消失,但是每当我添加任何 jquery datepicker 选项时-该值就会消失!?

【问题讨论】:

  • @bresleveloper 请停止为 plunkers 或 jsfiddles 打扰人们。代码必须在问题中,而不是在外部代码托管服务中。

标签: javascript jquery html datepicker


【解决方案1】:

我认为问题出在你的初始化中,试试这个:

$(function(){

    $('.datepicker').each(function(){
        $(this).datepicker({"changeYear": true});
    });

});

这是一个有效的fiddle

【讨论】:

【解决方案2】:

稍后尝试此行以纠正问题:

$(".datepicker").each(function() {
    $(this).datepicker();
    $(this).datepicker("option", "changeYear", true);
    $(this).attr("value", "11-11-2016");
});

如果属性根据$(".datepicker") 是动态的,则使用以下内容:

function getElemAttributes(var element) {
    var attrs = {};
    var attrMap = element.attributes;

    $.each(attrMap, function (i, e) { attrs[e.nodeName] = e.nodeValue; });

    return attrs;
}

获取所有属性作为一个对象。所以:

$(".datepicker").each(function() {
    $(this).datepicker();

    // Returns something like { id: "datepicker", ..., value: "11-11-2016" }
    var originalAttributes = getElemAttributes(this);

    // Do stuff that affects attr on element.
    $(this).datepicker("option", "changeYear", true);

    // Set element attributes from riginal attributes object.
    if (originalAttributes.hasOwnOroperty("value")) {
        $(this).attr("value", originalAttributes["value"]);
    }
    else {
        // Didn't originally have a "value" attribute - set some default here?
    }
});

【讨论】:

  • 首先我得到Uncaught SyntaxError: Unexpected token var,删除var后我得到Uncaught TypeError: originalAttributes.hasOwnOroperty is not a function
【解决方案3】:

您应该使用此选项来设置初始日期:

$( ".selector" ).datepicker( "setDate", "10/12/2012" );

在你的代码示例中:

  $(".datepicker").each(function() {
    $(this).datepicker();
    $(this).datepicker("option", "changeYear", true);
    $(this).datepicker( "setDate", "10/12/2012" );
  });

【讨论】:

  • 当我将它与$(this).val() 一起使用而不是您编造的日期时,由于格式的原因,我得到了错误的日期(我在我的值中使用了“11-11-2016”)。如果我首先设置格式选项,该值会再次消失...。
【解决方案4】:

你需要这个:

$(document).ready(function () {

$('.datepicker').each(function(){
    $(this).datepicker();
    $(this).datepicker("option", "changeYear", true);
    $(this).datepicker( "setDate", $(this)[0].getAttribute('value') );
});

【讨论】:

    【解决方案5】:

    这个命令帮助我解决了像你这样的问题:

    let date = $(this.dateInput.nativeElement).val().toString();
    ....
    $(this.dateInput.nativeElement).datepicker().val(date).trigger('change');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多