简体   繁体   中英

Rails jQuery not working in asset pipeline

When I place this jQuery code in the view file, it works fine:

$('.messages-link').click(function (event) {
  $.getScript(this.href);
  history.pushState(null, "", this.href);
});

But when I put it in useful.js, and require useful.js in application.js, it doesn't work, it isn't called.

application.js

//= require jquery
//= require jquery-ui
//= require jquery_ujs
//= require bootstrap
//= require underscore
//= require useful

I know that useful.js is successfully being included in the asset pipeline because there is another function in there that is definitely being called from the same view file.

Why does the jQuery function not work?

The reason for this is that if you put it in your view the element .messages-link exists in the DOM.

If you put it in useful then the file gets bundled in application.js and it is loaded in the <HEAD></HEAD> on your html before the view that has .messages-link is loaded.

A possible solution is to change the binding like this:

$('.messages-link').on('click', function (event) {
  $.getScript(this.href);
  history.pushState(null, "", this.href);
});

Which works with dynamically added elements.

Have you forgotten to place your code inside a DOM ready function? Perhaps your DOM has not loaded before you try to attach the listener?

$(function() {

  $('.messages-link').click(function (event) {
    $.getScript(this.href);
    history.pushState(null, "", this.href);
  });

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM