[英]How to make this jQuery function more elegant?
On my page I have a drop-down select box, with a default value of (empty). 在我的页面上,我有一个下拉选择框,默认值为(空)。 When the user selects an entry, the appropriate form for that entry type is displayed.
当用户选择一个条目时,将显示该条目类型的适当形式。
Couple of problems.. 几个问题。
.change()
event, the form box is not displayed. .change()
事件,因此表单框不显示。 They have to select a different <option>
, then click back to their original choice to get their forum back. <option>
,然后单击返回其原始选择以返回论坛。 Here's the code: 这是代码:
<script type="text/javascript">
$(document).ready(function(){
$('#select_type').change(function () {
$('fieldset').css('display','none'); # hide all the forms on the page
var selectval = $('#select_type').val();
if (selectval == 'instance')
{
$('#instance').toggle();
}
if (selectval == 'mob')
{
$('#mob').toggle();
}
if (selectval == 'dailyquest')
{
$('#dailyquest').toggle();
}
if (selectval == 'repeatablequest')
{
$('#repeatablequest').toggle();
}
if (selectval == 'zonequest')
{
$('#zonequest').toggle();
}
if (selectval == 'reward')
{
$('#reward').toggle();
}
});
});
</script>
Help JS gurus of SO! 帮助JS大师!
Instead of the multiple IF clauses, you can iterate over an array of values. 您可以遍历值数组来代替多个IF子句。 But in this case, if there are no other requirements then simply:
但是在这种情况下,如果没有其他要求,则只需:
$(document).ready(function(){
var select = $('#select_type');
$('#' + select.val()).toggle(); // Toggle the preset value
select.change(function () {
$('fieldset').css('display','none');
$('#' + $(this).val()).toggle();
});
});
Should be enough. 应该足够了。
$(document).ready(function() {
$("#select_type").change(function () {
$("fieldset").css("display", "none");
$("#" + $(this).val()).toggle();
}).change();
});
I probably wouldn't use a select box, as select boxes are only a good choice when the options are known to the user before they pull it down. 我可能不会使用选择框,因为只有当用户在下拉选项之前就知道这些选项时,选择框才是一个不错的选择。 No mystery meat allowed.
不允许使用神秘的肉。 Here is a good article on selection dependant inputs .
这是一篇关于选择相关输入的好文章。
My take on this problem: * Only the section linked to the selected option should be shown, so I don't want to use toggle. 我对这个问题的看法:*仅应显示链接到所选选项的部分,所以我不想使用切换。
$(function(){
var sel = $("#select_type");
$("#"+sel.val()).show();
sel.change(function(){
$(this).children("option").each(function(){
$("#"+this.value)[this.selected ? "show" : "hide"]();
});
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.