[英]Jquery on('click') with dynamic button ID
I have a comment's reply form which is loop through database, each of the form and reply button are dynamically assigned with difference ID, such as <button type="button" id="btn_reply_comment_'.$row['id'].'">Post Reply</button>
as well as a form ID with <form id="reply_form_'.$row['id'].'">
. 我有一个通过数据库循环的评论回复表单,每个表单和回复按钮都动态分配有差异ID,例如
<button type="button" id="btn_reply_comment_'.$row['id'].'">Post Reply</button>
以及带有<form id="reply_form_'.$row['id'].'">
的表单ID。
I want to make an ajax call trigger by the #btn_reply_comment_{follow by dynamic ID}
, but I cannot assign dynamic ID to match with which button is clicked, how can it be done? 我想通过
#btn_reply_comment_{follow by dynamic ID}
进行Ajax调用触发,但是我无法分配动态ID来与单击哪个按钮匹配,该怎么做?
Jquery to trigger ajax by button click: jQuery通过单击按钮触发ajax:
$('body').on('click', '#btn_reply_comment_'+id, function(){
var parameters = $(this).closest('form').serialize();
alert(parameters);
//ajax call here
});
html HTML
<button id="btn_reply_comment_'.$row['id'].'" class="className">Post Reply</button>
jquery jQuery的
$(".className").click(function(){
var parameters = $(this).closest('form').serialize();
alert(parameters);
//ajax call here
});
You should use a class for this. 您应该为此使用一个类。 And set up the click handler on teh class.
并在该类上设置点击处理程序。
So your HTML might look like: 因此,您的HTML可能如下所示:
<button type="button" id="btn_reply_comment_'.$row['id'].'" class="post_reply_button">Post Reply</button>
And your jQuery would look like: 而且您的jQuery看起来像:
$('body').on('click', '.post_reply_button', function(){
var parameters = $(this).closest('form').serialize();
alert(parameters);
//ajax call here
});
Stash the ID on the elements themselves. 将ID存储在元素本身上。 No need to use string manipulation.
无需使用字符串操作。
HTML HTML
"<button type="button" class="btn_reply_comment" data-rowid="'.$row['id'].'">"
"<form id="reply_form" data-rowid="'.$row['id'].'">"
Javascript 使用Javascript
$('body').on('click', '.btn_reply_comment', function(){
var rowId = $(this).data('rowid'),
parameters = $('form[data-rowid=' +rowId + ']').serialize();
alert(parameters);
//ajax call here
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.