【问题标题】:jQuery: onchange function of a <select> id only fires after reloadjQuery:<select> id 的 onchange 函数仅在重新加载后触发
【发布时间】:2014-09-08 17:13:21
【问题描述】:

我在 Rails 4.1 中有一个应用程序。我正在使用 jquery-rails 3.0。

我有以下 javascript 文件 welcome.js 加载 jQuery 和 等待 onchange 事件通过更改 DOM 中具有特定 ID 的 &lt;select&gt; 来触发:

jQuery(document).ready(function(){
  var width_of_grams = $(window).width(); //TODO why is this being called here?
  var new_pic_height = (width_of_grams /7);
  $("img.gram_photo").css('height', (width_of_grams) / 7);
  $("#instafeed").css('height', 2*new_pic_height);

  $(window).resize(function() {
    var width_of_grams = $(window).width();
    var new_pic_height = (width_of_grams /7);
    $("img.gram_photo").css('height', (width_of_grams) / 7);
    $("#instafeed").css('height', 2*new_pic_height);
  });


  $("#school_application_fls_center").change(function(){
    console.log("Hey man why are you sleeping?");
    var center_id = document.getElementById("school_application_fls_center").value;
    var formdata = {center: center_id};
    $.ajax({
        url: "/application/get_programs_for_center",
        type: "POST",
        datatype: 'json',
        data: formdata,
        success: function(response){
          var options = $("#school_application_program");
          removeOptions(document.getElementById("school_application_program"));
          $.each(response.programs, function(i,item) {
            options.append($("<option />").val(response.programs[i].id).text(response.programs[i].name));
          });
        }
    });
  });
});

.change 函数仅在我使用school_application_fls_center id 重新加载页面后调用。否则,即使我更改了&lt;select&gt;,它也不会被触发,我看不到我的console.log,当然,Rails 也没有收到应该由该事件触发的POST 请求。

同样的现象也发生在 Chrome、Safari、Firefox 和 Opera 上。

注意有趣的是,当视口发生变化时,.resize 事件被成功调用。

【问题讨论】:

    标签: javascript jquery ruby-on-rails ajax


    【解决方案1】:

    您应该停用 turbolinks gem...它与 jquerying 的东西一团糟

    编辑

    您可以使用 jquery-turbolinks gem 让您的事件与 turbolinks 绑定

    【讨论】:

    • 你怎么知道我安装了那个 gem?
    • 是的!无限感谢您对 rails 4.1 的直觉
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-04
    • 1970-01-01
    • 2021-07-08
    • 1970-01-01
    • 1970-01-01
    • 2012-09-02
    • 1970-01-01
    相关资源
    最近更新 更多