2017-04-15 46 views
0

我有一個頁面,其中多個職位來自數據庫和這些職位上可以發表評論 時,我正在做一些AJAX調用POST按鈕 當前我只有5篇文章我 主頁的問題是POST按鈕僅在第一篇文章我看到的響應文本解析之前,做工精細,並解析後,但是當我在其他文章張貼按鈕點擊我的控制檯犯規表現出任何事情我的繼承人代碼jquery post按鈕

{' 
$(document).ready(function() 
{ 
//this will fire only when page is fully loaded 
$('#comment-post-btn').each(function() 
{ 
    $(this).click(function() 
    { 
console.log("Button is working fine"); 
comment_insert_btn_click(); 
    }); 
}); 
function comment_insert_btn_click() 
{ 
var _comment=$('#comment-post-text').val(); 
var _userId=$("#userId").val(); 
var _userName=$("#userName").val(); 
if(_comment.length > 0 && _userId!=null) 
{ 
console.log(_comment + "UserId: " + _userId + "UserName: " + _userName); 
$.post("comment-insert.php" , 
    { 
     task : "comment-insert", 
     userId : _userId, 
     comment: _comment 
    }, 
     function(data)   
     {  
      console.log("ResponseTextBeforeParsing " + data); 
      data = JSON.parse(data) 
      console.log("ResponseTextAfterParsing " + data); 

      comment_insert(data); 
      console.log("ResponseTextAfterParsing " + data); 

     } 
    ) 
$('.comment-insert-container').css('border' , ' 1px solid #fffff0'); 
} 
else 
{ 
$('.comment-insert-container').css('border' , ' 1px solid #ff0000'); 
console.log("the text area was empty"); 
} 

$('#comment-post-text').val(""); 
} 
'} 
+1

您不能對一個DOM元素使用一個ID。將它們更改爲類 –

+0

元素標識必須是唯一的。重複無效。 – Jasen

+0

如果我得到你的權利,然後我不能使用類作爲帖子來自數據庫,我需要啓用此按鈕來自數據庫的每一個職位 –

回答

0

您不需要使用.each()註冊點擊次數,並且重複的ID無效。所以你要麼設計一個系統來生成唯一的id或者使用class屬性。

$(".comment-post-btn").on("click", function(e) { 
    var me = $(this); // the instance that triggered the click 

}); 

由於它看起來像是在嘗試獲取表單值,因此需要將表單提交進行陷阱。

$("form.my-form-class").on("submit", function(e) { 
    e.preventDefault(); 

    var form = $(this); 
    var data = form.serialize(); 
    var comment = form.find("textarea[name='comment']").val(); 

    $.ajax({ 
     ... 
    }); 
}); 
+0

我必須在單個事件中做到這一點,你可以請告訴我怎麼可以我在這裏使用class屬性? –

+0

我不明白你的問題。單一事件是什麼意思? – Jasen

+0

我怎樣才能動態地改變我發佈的按鈕的ID,這樣它就可以爲來自數據庫的每一個帖子工作,並且我應該把#comment-post-btn放在jquery中,我之前提到過按鈕的ID –