2017-04-21 126 views
-2

我添加了一个脚本来触发输入事件,它可以正常工作,直到我们滚动页面。当我们滚动时,它会动态地添加另一个页面(它是ajax调用),但是从第二页脚本不加载。页面滚动后Javascript未加载

这是代码:

<%= form_tag add_comments_statuses_path, :data => {:toggle => "validator"}, :html => {:class=>"form-horizontal row-fluid shift_from", :id => "comments_form_#{status}"}, method: :post, :remote => true do %> 
    <div class="control-group"> 
    <a href="#" class="cmt-thumb"> 
     <%= image_tag current_user.profile_pic, :style=>"width:40px!important; height:40px;" %> 
    </a> 
    <div class="controls cmt-form " style="margin-bottom:10px;"> 
     <%= text_area_tag 'comment', " ", :class => "form-control", :id => "comment-form-#{status}", :placeholder =>"Write a comment...",:data => {:error => "Please Enter Comment"}, required: true %> 
     <span class="help-block with-errors" id = "error-#{status}"></span> 

    </div> 
    </div> 
    <input type="hidden" value="<%= status %>" name="status_id"> 
<% end %> 


<script> 
    $(function(){ 
    $("#comment-form-<%= status %>").keypress(function(event) { 
     if (event.which == 13) { 
      event.preventDefault(); 
      if ($(this).val() != " ") 
      $(this).closest('form').submit(); 
     } 
    }); 
    }) 
</script> 
+0

你不是说ajax调用我猜测,原因,因为ajax调用是异步的,这意味着当它不甚至完整意味着ajax结果将被显示意味着他的DOM不是'生活'尝试$(“#comment-form- <%= status %>”).delegate 'keypress'function(event){your code;}); –

回答

0

它不滚动之后在第二页,因为新页面无法识别按键事件,因为新增加的HTML不是在最初的DOM存在工作。

要解决此问题,你必须编写按键事件直列,并从那里调用函数如下:

<input type='text' onkeypress = "return yourFunction(event)"/> 

注:请检查onkeypress事件事件调用语法一次

+0

谢谢,我改变了完整的代码。现在它工作正常。 – sahu

+0

对不起,我想upvote,但它有一些错误信息 – sahu