jquery show hide div基于选择值
我有一个选择列表,其中包括“全部”和“自定义”。 在选择值为’custom’时,应显示带有“资源”类的div,如果值为“all”则应隐藏。
表格是:
All Custom resources
这个javascript是这样的:
ShowPrivileges: function() { var Privileges = jQuery('#privileges'); var select = this.value; Privileges.change(function() { if (select === 'custom') { $('.resources').show(); } }); }
为了工作,这应该怎么样? 对不起,我知道这应该很简单,但我对这一切都很新。
你需要使用val方法:
var Privileges = jQuery('#privileges'); var select = this.value; Privileges.change(function () { if ($(this).val() == 'custom') { $('.resources').show(); } else $('.resources').hide(); // hide div if value is not "custom" });
Privileges.on('change',function(){ if($(this).val()=='custom'){ $('.resources').show(); }else{ $('.resources').hide(); } })
您将要添加事件处理程序:
$("#privileges").change(craateUserJsObject.ShowPrivileges);
然后,在你的ShowPrivilegesfunction中:
var val = $("#privileges").val(); if(val == "whatever") //do something else //do something
$("#privileges").change(function(){ var select= $(this).val(); if(select=='custom'){ //some code } });
要么
var select=$('#privileges :selected').val() if(select=='custom'){ //some code }
你这太复杂了:
首先,放下内联onclick
。 由于您使用的是jQuery,因此请动态附加处理程序。
其次,不要监听点击,然后附加change
处理程序。 直接附上它
您可以通过删除onClick并从选项中删除ID来清理HTML。
HTML:
你的JavaScript可以简单地做到这一点:
$('#privileges').on('change', function() { if($(this).val() === 'all') { $('.resources').hide(); } else { $('.resources').show(); } });