2017-04-21 128 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