0

我有一个使用 UJS 的工作渲染部分,但是:

部分正在更新触发 onchange 操作的表单标记,然后,不再在这个新更新的标记上触发 javascript。

因此,下面的代码可以工作一次,然后就不再工作了。

我认为 UJS 绑定到 是在第一次加载(document.ready)时完成的,但不是在部分更新的元素上

--> 如何在从 ajax 请求返回的新标记上绑定相同的操作?--> 是否可以在加载文档时再次触发 UJS 函数的“绑定”?我需要创建一个额外的功能吗?

标记:

<form action="/loopview/1/show" data-remote="true" id="breadcrumb_form" method="post">
  <select class="auto_update">
   <option value="1970" selected="selected">test</option>
  </select>
</form>

乌兹别克斯坦:

$(document).ready(function() {
    ...
    $('select.auto_update').change(function(){ 
        ...
        $(this).submit();        // never triggered on newly loaded markup
    });
}
4

2 回答 2

0

我通过创建一个名为的外部函数来解决它:

  • 加载文档时一次
  • 每次更新标记时

代码 :

$(document).ready(function() {
    ... 
    bind_auto_update_action();
});



/* (Re)associate the correct event listeners to the markup. Is called at each refresh of the markup to (re)bind the listeners. */
function bind_auto_update_action() {
    /* Auto update the url when changing the value of one of the select in the breadcrumbs */
    $('select.auto_update').change(function(){ 
        $('#breadcrumb_point_id').val($(this).val());
        $(this).submit();
        console.log("Auto update function ");
    });

    /* Update the content of the main div with the returned markup from the serveur */
    $("#breadcrumb_form").bind('ajax:complete', function(status, data, xhr){
        $("#loopview_content").html(data.responseText);
        bind_auto_update_action();
        console.log("Update of the loopview_content <div> due to ajax response (breadcrumb navigation)");
    });
}
于 2013-04-26T13:31:22.677 回答
0

另一个简单的解决方案是使用事件侦听器on而不是change.

那么JS代码是这样的:

$(document).ready(function() {

  $('select.auto_update').on('change', (function(){ 
    ...
    $(this).closest("form").submit();        // never triggered on newly loaded markup
  });
 });

两个变化:

  1. on取代change
  2. 提交表单但不提交选择器。

这样您的活动将永远存在,省去您为ready.

于 2013-04-26T15:22:37.570 回答