我不知道变量是否适合在这里使用。 因此,我在Concrete5中设置了一个块,允许列出几个小时的某些部门。
这是我的示例脚本:
<script type="text/javascript">
$(function () {
$("#Saturdayopen").datetimepicker({
"pickDate":false,
"pickTime":true,
"useMinutes":true,
"useSeconds":false,
"useCurrent":false,
"showToday":false,
"useStrict":false,
"sideBySide":false,
"minuteStepping":1,
"minDate":"",
"defaultDate":"",
"icons ":{
"time":"glyphicon glyphicon-time",
"date":"glyphicon glyphicon-calendar",
"up":"glyphicon glyphicon-chevron-up",
"down":"glyphicon glyphicon-chevron-down"},
"language":"en",
"disabledDates":[],
"enabledDates":[],
"daysOfWeekDisabled":[]});
});
</script>
问题是我需要每次为每周的每一天使用相同的脚本两次。所以我在同一个文件中有14个这样的脚本。有什么办法可以将代码压缩成一个脚本吗?
例如,在这一行:
$("#Saturdayopen").datetimepicker({
有没有办法添加#Saturdayclosed,#Sundayopen等等?
答案 0 :(得分:0)
这实际上不需要对Concrete5做任何事情,但它与Javascript有关。 <击> 变量在这里不是正确的术语,您正在寻找一种向jQuery选择器添加多个元素的方法。 jQuery使用CSS选择器,所以你可以像在CSS中一样:string'em和逗号:
$("#Saturdayopen, #Sundayopen, #etcetera").datetimepicker({...
击> <击> 撞击>
这可能是由于您正在使用的.datetimepicker()
插件的限制。您可以使用for
循环轻松修复:
var days = ["#Saturdayopen", "#Sundayopen", "#etc"];
for(var i = 0; i < days.length; ++i){
$(days[i]).datetimepicker({
//options
});
}
您可能还可以在代码示例中删除一些默认参数,这些参数应该将其整理得很多。
答案 1 :(得分:0)
您正在使用daysOfWeekDisabled
和datetimepicker
来控制哪些日期已启用?
如果你的目标是压缩代码,你可以声明一些可以重用的默认值而不是创建14个匿名对象。这可能比批处理更灵活,除非每个var DateTimePicker = {
//return a new copy of the defaults
Defaults: function() {
return {
"pickDate": false,
"pickTime": true,
"useMinutes": true,
"useSeconds": false,
"useCurrent": false,
"showToday": false,
"useStrict": false,
"sideBySide": false,
"minuteStepping": 1,
"minDate": "",
"defaultDate": "",
"icons ": {
"time": "glyphicon glyphicon-time",
"date": "glyphicon glyphicon-calendar",
"up": "glyphicon glyphicon-chevron-up",
"down": "glyphicon glyphicon-chevron-down"
},
"language": "en",
"disabledDates": [],
"enabledDates": [],
"daysOfWeekDisabled": []
}
}
}
/*
JSON.stringify [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify]
prints the results of a JSON object so we can view the results
$.extend [https://api.jquery.com/jquery.extend/] will merge any override settings into the defaults
*/
//lets set Saturday as open
$("#Saturdayopen").html(JSON.stringify($.extend(DateTimePicker.Defaults(), {
enabledDates: ["Saturday"]
})));
//now lets try setting Saturday as closed
$("#Saturdayclosed").html(JSON.stringify($.extend(DateTimePicker.Defaults(), {
daysOfWeekDisabled: ["Saturday"]
})));
/*daysOfWeekDisabled
using this in your code would look like
$("#Saturdayopen").datetimepicker($.extend(DateTimePicker.Defaults(), {enabledDates:["Saturday"]}));
$("#Saturdayclosed").datetimepicker($.extend(DateTimePicker.Defaults(), {daysOfWeekDisabled:["Saturday"]}));
*/
的属性始终相同。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Saturday Open:
<div id="Saturdayopen"></div>
</div>
<br />
<div>Saturday Closed:
<div id="Saturdayclosed"></div>
</div>
max-height: 100vh