我有一个 div,仅当从下拉菜单中选择某个值时才显示该 div(在本例中为 custom-css
)
在 fiddle (http://jsfiddle.net/obmerk99/8xnzh/1/)上它工作正常......
jQuery(document).ready(function() {
jQuery("#k99-custom-1").change(function () {
jQuery("#k99-custom-1 option:selected").each(function ()
{
if( jQuery(this).attr("value") == "custom-css")
{
jQuery("#customcss").show();
}
else
{
jQuery("#customcss").hide();
}
});
}).change();
});
但在真实页面中,选择下拉列表实际上是使用“添加选项”按钮动态生成的,因此页面加载(文档就绪)时某些(第一个)选择不存在,我认为这就是原因它不起作用..
查看完整的操作(不起作用):http://jsfiddle.net/obmerk99/ZcAzy/1/
如果选择“custom-css”值,为了显示 div,我做错了什么? (现在它设置为仅适用于第一个(或第二个) - 但如果能使其适用于所有添加的选择列表就太好了..)
最佳答案
尝试使用委托(delegate)
,如下所示:
jQuery(function() {
// Here, `.on` is used in its `delegate` form, where it asigns an event to any
// element matching the selector
// regardless when it was added to the DOM
jQuery(document).on('change', "[id^='k99-custom-']", function(e) {
jQuery("[id^='k99-custom-'] option:selected").each(function(i) {
if (jQuery(this).attr("value") == "custom-css") {
jQuery("#customcss").show();
}
else {
jQuery("#customcss").hide();
}
});
})
})
我刚刚注意到在另一个答案的评论中,你尝试了这样的事情。您做错的是将选择器 [id^='k99-custom-']
的 event
委托(delegate)给 [id^='k99-custom-' ]
,正如您所看到的,它就是它本身。要进行委托(delegate),您需要指定一个父元素或 document
本身,如我的示例所示。最常见的用法就是使用 $(document).on(...
Example
关于javascript - 根据选择框更改 DIV 可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17434793/