[英]jquery click event on dynamically generated element
I am trying to bind a click event to buttons attached to each form in a dynamically generated list of forms.我试图将一个点击事件绑定到一个动态生成的表单列表中的每个表单上的按钮。 There's a simplified version below.
下面有一个简化版。 each form will have, delete, edit, save and cancel buttons.
每个表单都有删除、编辑、保存和取消按钮。 The save and cancel buttons should be hidden from the start.
保存和取消按钮应该从一开始就隐藏起来。 When the edit button is pressed the save and cancel buttons should show but only for the form who's button was pressed.
当按下编辑按钮时,保存和取消按钮应该显示,但仅适用于按下按钮的表单。 The value shown in the table should be hidden and replaced with replaced with an input element.
表中显示的值应隐藏并替换为替换为输入元素。
$count = 0;
$content = '';
$array = array('car', 'dog', 'plane');
foreach ($array as $value){
$content .="
<form id='form' method='post'>
<div class='list'>
<table>
<tr>
<td style='font-weight: bold;'>Program</td>
<td class='value_$count'>$value</td>
<td class='edit_value_$count'><input name='value' type='text' id='value' value='$value'></td>
</tr>
</table>
<input name='delete' action='' type='submit' id='delete' value='Delete'>
<input name='save' action='' type='submit' id='save' value='Save'>
<button id='edit_$count'>Edit</button>
<button id='cancel_$count'>Cancel</button>
</div>
</form>
";
$count++;
}
echo $content;
I am stuck on the java script to make this happen.我坚持使用java脚本来实现这一点。 It would be something like the code bellow if there was only one form.
如果只有一种形式,它将类似于下面的代码。 How would you do it so it applied to all the forms generated???
你会怎么做,使它适用于所有生成的表格???
$("#edit_").show();
$("#cancel_").hide();
$("#save").hide();
$(".edit_value_").hide();
$(".value_").hide();
$("#edit_").click(function(){
$("#edit_").hide();
$("#save").show();
$("#cancel_").show();
$(".edit_value_").show();
$(".value_").hide();
});
You need to update your code from你需要更新你的代码
$("#edit_").click(function(){
....
});
to到
$(document).on("click", '[id^="edit_"]', function(){ // binding click event to all those elements having id starting with edit_
var index = $(this).attr('id').split("_")[1]; // extracting the counter from id attribute of edit button
$("#cancel_"+index).show(); // using index
.........
});
Please note, for event binding on dynamically added elements, use .on
.请注意,对于动态添加的元素的事件绑定,请使用
.on
。
You need to update your Code for id="edit_"
instead of id
use class
.您需要为
id="edit_"
而不是id
use class
更新您的代码。 Then it will work.然后它会起作用。
HTML should HTML 应该
<button id='edit_$count' class="edit_">Edit</button>
Jquery code查询代码
$(".edit_").click(function(){
$(".edit_").hide();
$("#save").show();
$("#cancel_").show();
$(".edit_value_").show();
$(".value_").hide();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.