2017-10-14 123 views
0

我有一個非常簡單的jquery函數,它模仿許多在線教程中的代碼,我已經看過幾個類似的stackoverflow問題,但我不明白爲什麼沒有任何反應,當我點擊鏈接顯示/隱藏名爲「高級搜索」的div。 (我也刪除了turbolink,但沒有任何反應,我在應用程序中還有其他的Jquery代碼,所有工作都很好)。簡單的jquery切換不工作

文章/ index.html.erb

<div class="advanced-search"> 
     Some code 
    </div> 

    <a class="show-advanced-search">Advanced Search</a> 

articles.js

$(document).ready(function(){ 
    $('.show-advanced-search').click(function(){ 
    $('.advanced-search').toggle(); 
    }); 
}); 

縮小選擇向下'a.show-advanced-search'也不起作用。

編輯:

我有一個名爲「articles.coffee」下面用Ajax回調是另一個jQuery的文件,認爲這可能會影響其他jQuery代碼之一。不過,我試過刪除「articles.coffee」,同樣的問題依然存在。

將articles.js中的代碼複製並粘貼到瀏覽器控制檯中。瀏覽器控制檯沒有錯誤。

articles.coffee

jQuery(document).on 'change', 'select.sortBy',() -> 
    $.ajax(
    url: $(this).data('url') + '?type=' + this.value 
    type: 'GET' 
    contentType: 'script' 
    processData: false 
) 
    return 

如果它在同一時間的頁面加載,它不應該出現任何錯誤加載我原來的application.js文件

//= require rails-ujs 
//= require jquery 
//= require bootstrap-sprockets 
//= require jquery_ujs 
//= require jquery.transit.js 
//= require turbolinks 
//= require articles.js 
//= require_tree . 
+0

瀏覽器控制檯中的任何錯誤?在腳本代碼之前添加了jQuery庫嗎?你有沒有在當前的HTML文件中包含你的js文件? –

+0

我無法複製它 – brk

+0

@AlivetoDie jQuery代碼只有在我將其粘貼到控制檯並啓動它時才起作用。是的,我添加jQuery庫 – doyz

回答

0

。但是,如果這是出現點擊一個按鈕後,你應該試試這個彈出的部分代碼:

<pre>$(document).ready(function(){ 
    // we assum the pop-up container loads at the same time the page is loaded 
    $('div.pop_up_container').on("click",".show-advanced-search",function(){ 
    $(this).next('.advanced-search').toggle(); 
    }); 
});</pre> 
0

喜試圖以此爲articles.js

$(document).ready(function(){ 
    $('.show-advanced-search').click(function(){ 
    $('.advanced-search').toggle(); 
    }); 
}); 

jsfiddle

0

如果您已包含jquery.jsarticles.js的順序。那麼下一個問題可能是turbolinks如果你正在使用它。

$(document).on('turbolinks:load', function() { 
    // Do your code 
}) 

注:上滑軌> = 4有它的。請檢查。

0

我通過結合articles.coffee和articles.js文件來修復它。

articles.coffee

jQuery(document).on 'click', 'a.show-advanced-search',() -> 
    $('.advanced-search').toggle() 

好像有2個獨立的文件,甚至無論是在application.js中不起作用指定。