jQuery UI 日期选择器的属性选项

Attribute options for jQuery UI datepicker

我有这个带有 data-options 属性的输入。

<input class="data" type="text" data-options="{maxDate:'0'}" />

我想使用 data-options 值作为选项加载 datepicker。现在使用以下代码,不起作用

$("input.data").each(function(){
    var dateOptions=$(this).data('options');
    $(this).datepicker(dateOptions)
});

但是如果我像下面的代码一样把选项放在 js 上,它就可以工作:

$("input.data").each(function(){
    $(this).datepicker({maxDate:'0'})
});

https://jsfiddle.net/VixedS/exfLf6o9/

If is somebody can, I would prefer an answer without eval.

当你调用 data 函数时,它是 returns 字符串,所以你必须将它转换为一个对象,然后将它传递给 datepicker 并从 [= 的值中删除大括号21=].

解决方案:

1- 使用 eval

Javascript

eval('({' + $(this).data('options') + '})')

HTML

data-options="maxDate:'0'"

2- Jquery .data 并用 '

包围您的数据属性值

Javascript

$(this).data('options')

HTML

data-options='{"maxDate":0}'

3- 使用 plugin or write custom function(the below code is written by @allenhwkim).

Javascript

function JSONize(str) {
  return str
    // wrap keys without quote with valid double quote
    .replace(/([$\w]+)\s*:/g, function(_, ){return '"'++'":'})    
    // replacing single quote wrapped ones to double quote 
    .replace(/'([^']+)'/g, function(_, ){return '"'++'"'})         
}

jQuery.parseJSON(JSONize($(this).data('options')));

HTML

data-options="{maxDate:'0'}"

注意:以上所有解决方案都经过测试并且有效。

$("input.dataWithoutOptions").each(function() {
  $(this).datepicker({
    maxDate: '0'
  })
});

$("input.data").each(function() {
  var dateOptions = eval('({' + $(this).data('options') + '})');

  console.log(typeof($(this).data('options'))); //String

  console.log(typeof(dateOptions)); //Object


  $(this).datepicker(dateOptions)
});
input {
  display: block;
  margin: 10px 0 20px;
  padding: 5px;
}
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.3/jquery-ui.min.js"></script>


This has options attr:
<input class="data" type="text" data-options="maxDate:'0'" />This is just a date pick:
<input class="dataWithoutOptions" type="text" />

Jsfiddle

Jquery数据自动将JSON字符串解析为对象。您只需按照 jQuery.parseJson()

的指示进行操作

http://api.jquery.com/jquery.parsejson/

将您的选项从 data-options="{maxDate:'0'}" 更改为 data-options='{ "maxDate": 0 }' 创造奇迹

编辑:2015 年 12 月 28 日

由于在 XHML 中您不想对属性使用单引号 ',您可以反其道而行之,然后将单引号替换为双引号,然后解析 json 响应。 { 'maxDate': 0 } 然后 .replace(/'/g, '"') 并使用 $.parseJSON()

$("input.dataWithoutOptions").each(function() {
   $(this).datepicker({
     maxDate: '0'
   })
 });

 $("input.data").each(function() {
   var dateOptions = $.parseJSON($(this).data('options').replace(/'/g, '"'));
   $(this).datepicker(dateOptions);
 });
input {
     display: block;
     margin: 10px 0 20px;
     padding: 5px;
   }
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.3/jquery-ui.min.js"></script>

This has options attr:
<input class="data" type="text" data-options="{ 'maxDate': 0 }" />This is just a date pick:
<input class="dataWithoutOptions" type="text" />

编辑:2015 年 12 月 30 日

@Lidaranis:提出了一个很好的观点。

您可以使用转义字符来避免正则表达式和解析 json。 {&quot;maxDate&quot;:0}

$("input.dataWithoutOptions").each(function() {
  $(this).datepicker({
    maxDate: '0'
  })
});

$("input.data").each(function() {
  var dateOptions = $(this).data('options');
  $(this).datepicker(dateOptions);
});
input {
  display: block;
  margin: 10px 0 20px;
  padding: 5px;
}
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.3/jquery-ui.min.js"></script>

This has options attr:
<input class="data" type="text" data-options="{&quot;maxDate&quot;:0}" />This is just a date pick:
<input class="dataWithoutOptions" type="text" />

试试这个,

选项 - 1

将 JavaScript 更改为

$("input.data").each(function(){
  var dateOptions=$(this).data('options');
  var options = dateOptions.split(', ');
  var obj = {};
  options.forEach(function(opt) {
      var item = opt.split(':');
      obj[item[0]] = item[1];
  });

  $(this).datepicker(obj);
});

并将html更改为

<input class="data" type="text" data-options="maxDate:'0'"/>

没有 eval()

见javascriptfiddlehttps://jsfiddle.net/exfLf6o9/7/

选项 - 2

JavaScript

$("input.data").each(function(){
  var dateOptions=$(this).data('options');
  dateOptions = dateOptions.substring(1,dateOptions.length-1);
  var options = dateOptions.split(', ');
  var obj = {};
  options.forEach(function(opt) {
      var item = opt.split(':');
      obj[item[0]] = item[1];
  });

  $(this).datepicker(obj);
});

并保持 html 不变

看jsfiddlehttps://jsfiddle.net/exfLf6o9/8/

选项 - 3

将html改为

<input class="data" type="text" data-options='{"maxDate":"0"}' />

并在 javascript

$("input.data").each(function(){
  var dateOptions=$(this).data('options');
  $(this).datepicker(dateOptions);
});

不建议在 JavaScript

中使用 eval()

请参阅fiddlehttps://jsfiddle.net/exfLf6o9/5/

日期选择器函数需要一个对象,而当前您传递的是一个字符串,因此会出现错误。

data() returns 当 datepicker() 需要一个对象时的字符串。解决方法是将字符串转为对象:

$("input.data").each(function(){
    var dateOptions = $(this).data('options');
    var dateOptionsAsObject = JSON.parse(dateOptions.replace(/([\w|\-|\_]+:)/g,"\"\":"));
    $(this).datepicker(dateOptionsAsObject);
});

想放弃延迟加载技术,因为没有人提到它。

<div class="data" data-max-date="0"></div>

$.data() 将自动对您的数据属性进行驼峰式命名并尝试进行类型转换。即上面的html属性数据将变为:{ maxDate: 0 }

$('.data').each(function(){
  $this = $(this);
  $this.datepicker($this.data());
});