2013-07-02 28 views
0

我有,我想只顯示,如果某個值從下拉菜單中選擇(在這種情況下,它是custom-css基於選擇框更改DIV的知名度

在小提琴(http://jsfiddle.net/obmerk99/8xnzh/1/)一個div它的工作原理確定...

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? (現在它被設置爲只與第一個(或第二個)一起工作 - 但是它可以很好地與所有添加的選擇列表配合使用。)

+0

大聲笑,我在更新答案,當你選擇它,希望它可以幫助 – 2013-07-02 20:57:13

回答

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

我只是在另一個答案評論注意到,你嘗試過這樣的事情。你做錯了什麼是將選擇器[id^='k99-custom-']委託給[id^='k99-custom-'],如你所見,它本身就是。要進行委派,您需要將其指定給父元素或document本身,如我的示例中所示。最常見的用途就是使用$(document).on(...

Example

瞭解更多關於.delegate.on形式吧!

+0

很好的信息..它像一個魅力。我的JS技能<= NULL,但我想.. :-)非常感謝。 –

1

您需要使用on函數,而不是僅僅使用on函數change綁定到動態元素。

$('body').on('change','#k99-custom-1',function(){ 
    //function here 
}); 
+0

謝謝,似乎很邏輯,但不知何故它不工作,也許我做了其他事情錯誤.. http://jsfiddle.net/obmerk99/ ZcAzy/2/ –