![](/img/trans.png)
[英]jQuery on(“click”) not working after $(window).on('hashchange') and emptying main div
[英]jQuery window 'hashchange' switch statement efficiency
我正在显示基于URL哈希值的jQuery multiselect控件中的“选定”项目。 例如,
http://localhost/index#options=2,3,4
在基于URL hashQuery的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');
}
};
这与效率 (代码执行的速度)无关。 实际上,使用循环可能会使速度变慢。 它只是具有干净的代码 ,可以在您添加更多选项时正确地执行操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.