2016-08-03 18 views
0

我試圖在加載頁面時隱藏一些元素。隱藏特定元素onload或ready或page:如果選擇標記具有特定值,則更改

目前我使用的是'page:change',因爲我在使用Turbolinks的Ruby on Rails中工作。

如果div包含具有特定值的選擇標記,我想隱藏一些元素。
該頁面可以包含多個這些選擇標記,因此我無法使用ID。這裏

代碼不起作用:

$(document).on('page:change', function(){ 

    if ($('.q_type_select').val() == 'text' || $('.q_type_select').val() == 'area') { 
      $(this).closest('.question_fieldset').children('.choice_fieldset').hide(); 
      $(this).closest('.question_fieldset').children('.add_fields').hide(); 
     }; 
}; 

我想如果你單擊$(this)僅適用?

如果我這樣做:

$(document).on('page:change', function(){ 

    if ($('.q_type_select').val() == 'text' || $('.q_type_select').val() == 'area') { 
      $('.question_fieldset').children('.choice_fieldset').hide(); 
      $('.question_fieldset').children('.add_fields').hide(); 
     }; 
}; 

我得到所有具有該類隱藏,而不是我想要的那些元素。

有什麼建議嗎?

+0

只需使用$(文件)。就緒[導軌4 –

+0

可能的複製:如何使用$(document).ready()與turbo鏈接](http://stackoverflow.com/questions/18770517/rails-4-how-to-use-document-ready-with-turbo-links) –

+0

這是如何回答這個問題的?我沒有問這個問題,請閱讀這個問題。 – aleherzko

回答

1

假設你有什麼是正確的(因爲沒有HTML看起來)。通過所有的元素(.q_type_select)出現在頁面上的文檔準備功能和隱藏(的 試試這個

$(function(){ 
    $('.q_type_select').each(function(){ 
    var $this = $(this); 
    if ($this.val() == 'text' || $this.val() == 'area') { 
     $this.closest('.question_fieldset').children('.choice_fieldset').hide(); 
     $this.closest('.question_fieldset').children('.add_fields').hide(); 

    }; 
    }) 
}); 

環路)它

+0

正常工作,非常感謝。不知道這裏有'each'方法,很好。 – aleherzko

+1

再次sniped,哈哈。 – dlsso

+0

@aleherzko歡迎。快樂編碼。 – bipen

相關問題