Javascript jQuery窗口';hashchange';开关语句效率
我根据URL散列中的值在jQuery multiselect控件中显示“selected”项。比如说,Javascript jQuery窗口';hashchange';开关语句效率,javascript,jquery,Javascript,Jquery,我根据URL散列中的值在jQuery multiselect控件中显示“selected”项。比如说, http://localhost/index#options=2,3,4 基于url哈希查询呈现multiselect控件中的项目2、3和4“选定”。我的问题是如何定义窗口“hashchange”事件,这样我就不必考虑所有可能的值组合来确定要显示的内容。例如,以下是我已经开始的内容,以及我希望避免的内容,因为这是无效的 $(window).on('hashchange');
http://localhost/index#options=2,3,4
基于url哈希查询呈现multiselect控件中的项目2、3和4“选定”。我的问题是如何定义窗口“hashchange”事件,这样我就不必考虑所有可能的值组合来确定要显示的内容。例如,以下是我已经开始的内容,以及我希望避免的内容,因为这是无效的
$(window).on('hashchange');
if (hashQuery.option) {
switch (hashQuery.option) {
case '1':
$("#options option[value='1']").attr("selected", "selected");
break;
case '1,2':
$("#options option[value='1']").attr("selected", "selected");
$("#options option[value='2']").attr("selected", "selected");
break;
case '1,2,3':
$("#options option[value='1']").attr("selected", "selected");
$("#options option[value='2']").attr("selected", "selected");
$("#options option[value='3']").attr("selected", "selected");
break;
default:
//
}
}
如何使这一点变得更有效,并且仍能达到同样的效果?如果您有任何问题,请告诉我。您有一个选项值列表,所以请将其视为选项值列表。将其转换为一个数组,然后只需在数组中循环并为每个值选择选项
$(window).on('hashchange', function() {
var values = hashQuery.option.split(',');
// values is now an array like ['1', '2', '3']
// so just loop through it
var selector;
for (i = 0; i < values.length; i++) {
selector = "#options option[value='"+ values[i] +"']";
$(selector).attr('selected', 'selected');
}
};
$(窗口).on('hashchange',function()){
var values=hashQuery.option.split(',');
//值现在是类似于['1'、'2'、'3'的数组
//所以只要循环一下就可以了
var选择器;
对于(i=0;i
这与效率(代码执行速度)无关。事实上,使用循环可能会使速度稍微慢一点。这只是让干净的代码在添加更多选项时做正确的事情