2013-04-26 59 views
0

结合UJS .change()我有一个工作与UJS渲染部分,但:的Rails +的Javascript:在页面更新HTML,没有功能了

正在更新触发形式的标记局部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> 

UJS:

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

回答

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构建自定义功能。

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)"); 
        }); 
    } 
    
  • +0

    请参阅bind(ajax:complete)部分中也调用的bind_auto_update_action()。这是为我工作的东西:-) – 2013-04-26 13:33:18

    相关问题