Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/474.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Rails JS文件和布局_Javascript_Jquery_Ruby On Rails - Fatal编程技术网

Javascript Rails JS文件和布局

Javascript Rails JS文件和布局,javascript,jquery,ruby-on-rails,Javascript,Jquery,Ruby On Rails,我试图为rails站点构建一些页面,但是我的js文件被弄糊涂了。我想知道在仍然使用rails资产管道的情况下处理特定于页面的js的最佳实践是什么 我的猜测是,我的问题是由编译成一个文件的独立文件中的onload函数引起的,但我可能错了 我有一个运行以下javascript代码的登录页: $(document).ready(function() { getQuote(); $('#get-quote').on('click', getQuote); $('#bt

我试图为rails站点构建一些页面,但是我的js文件被弄糊涂了。我想知道在仍然使用rails资产管道的情况下处理特定于页面的js的最佳实践是什么

我的猜测是,我的问题是由编译成一个文件的独立文件中的onload函数引起的,但我可能错了

我有一个运行以下javascript代码的登录页:

$(document).ready(function() {
      getQuote();
      $('#get-quote').on('click', getQuote);
      $('#btn-twitter').on('click', function() {openURL(url);});
    });
function getQuote() {
      $.when($.ajax( {
      url: 'https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1',
      success: function(data) {
        var post = data.shift();
        var author = post.title;
        if($(post.content).text().length > 250) {
          getQuote();
        } else {
          var quote = $(post.content).text();
          setTweetText(quote, author);
          $('#quote-author').html(author);
          $('#quote-content').html(quote);
        }
      },
      cache: false
    })).then(function(){
      $('#content').show();
      $('#msg').hide();
    })
}

function openURL(url){
  window.open(url, 'Share', 'width=550, height=400, toolbar=0, scrollbars=1 ,location=0 ,statusbar=0,menubar=0, resizable=0');
}
var url = "";
function setTweetText(quote, author) {
  url = 'https://twitter.com/intent/tweet?text=' + encodeURIComponent(quote + " -" + author);
}
然后,一旦它们进入主页,布局模板将运行以下操作:

$(document).ready(function() {
    document.getElementById("dd-button").addEventListener("click", ddClicked);
    window.onclick = function(event) {
        if (!event.target.matches('#dd-button')) {
            document.getElementById("dd-menu").classList.remove("dd-show");
        }
    }

    function ddClicked() {
        console.log("dd clicked");
        document.getElementById('dd-menu').classList.add("dd-show");
    }
});
我在两个页面上都会出现如下错误:

Cannot read property 'addEventListener' of null


非常感谢您在订购我的代码时提供的任何帮助。

$对于jQuery来说是一个错误。。1.你不包括它或2。你在你的js文件后加载jQuery,并且
addEventListener
出错,这是因为它找不到任何具有该ID的元素。让我澄清一下,代码工作正常,因此如果我在登录页上,jQuery错误不会出现。问题是错误显示在不使用特定代码块的页面上。因此,如果我不在登录页上,那么我会收到一条jQuery消息。这有意义吗
Uncaught ReferenceError: $ is not defined