我有这个输入与data-options属性。
<input class="data" type="text" data-options="{maxDate:'0'}" />
我想使用数据选项值作为选项加载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.
解决方法
Jquery数据自动将JSON字符串解析为对象。你只需要遵循jQuery.parseJson()的指示,
http://api.jquery.com/jquery.parsejson/
更改您的选项从data-options =“{maxDate:’0′}”到data-options ='{“maxDate”:0}’作品奇迹
编辑:12/28/2015
由于在XHML中,您不希望使用单个“属性”,您可以进行相反操作,然后用double替换单引号,然后解析json响应。 {‘maxDate’:0} then.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" />
编辑:12/30/2015
@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="{"maxDate":0}" />This is just a date pick:
<input class="dataWithoutoptions" type="text" />