Javascript 动态生成元素上的jquery单击事件

Javascript 动态生成元素上的jquery单击事件,javascript,jquery,Javascript,Jquery,我试图将单击事件绑定到动态生成的表单列表中附加到每个表单的按钮。下面有一个简化版本。每个表单都有删除、编辑、保存和取消按钮。保存和取消按钮应从一开始就隐藏。当按下“编辑”按钮时,应显示“保存”和“取消”按钮,但仅适用于按下按钮的表单。表中显示的值应隐藏并替换为输入元素 $count = 0; $content = ''; $array = array('car', 'dog', 'plane'); foreach ($array as $value){ $content .="

我试图将单击事件绑定到动态生成的表单列表中附加到每个表单的按钮。下面有一个简化版本。每个表单都有删除、编辑、保存和取消按钮。保存和取消按钮应从一开始就隐藏。当按下“编辑”按钮时,应显示“保存”和“取消”按钮,但仅适用于按下按钮的表单。表中显示的值应隐藏并替换为输入元素

$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;

您需要从更新您的代码

$("#edit_").click(function(){
      ....
});


请注意,对于动态添加的元素上的事件绑定,请使用
。在

上,您需要更新
id=“edit”
的代码,而不是
id
使用
。那就行了

HTML应该

<button id='edit_$count' class="edit_">Edit</button>

和这里一样。将不同的按钮与不同的id关联#edit1、edit2或其他任何内容。这将不起作用,因为每次循环运行时id
edit\uu
都是递增的
$(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
       .........

});
<button id='edit_$count' class="edit_">Edit</button>
$(".edit_").click(function(){

    $(".edit_").hide();
    $("#save").show();
    $("#cancel_").show();
    $(".edit_value_").show();
    $(".value_").hide();

});