0

我有一个 div,只有在从下拉菜单中选择某个值时才显示(在这种情况下,它是custom-css

在小提琴(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,我做错了什么?(现在它设置为仅适用于第一个(或第二个) - 但让它适用于所有添加的选择列表会很棒..)

4

2 回答 2

3

尝试使用delegation,如下所示:

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();
            }
        });
    })
})

我刚刚在对另一个答案的评论中注意到,您尝试过这样的事情。您做错的是将eventof 选择器委托[id^='k99-custom-'][id^='k99-custom-'],如您所见,它本身就是。要委托,您需要分配给父元素或document本身,如我的示例所示。最常见的用法就是简单地使用$(document).on(...

例子

了解更多关于它.delegate.on它的形式!

于 2013-07-02T20:16:13.930 回答
1

您需要使用该on函数,而不仅仅是change绑定到动态元素。

$('body').on('change','#k99-custom-1',function(){
  //function here
});
于 2013-07-02T20:03:42.847 回答