繁体   English   中英

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

[英]jquery click event on dynamically generated 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;

我坚持使用java脚本来实现这一点。 如果只有一种形式,它将类似于下面的代码。 你会怎么做,使它适用于所有生成的表格???

$("#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();

});

你需要更新你的代码

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

$(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
       .........

});

请注意,对于动态添加的元素的事件绑定,请使用.on

您需要为id="edit_"而不是id use class更新您的代码。 然后它会起作用。

HTML 应该

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

查询代码

$(".edit_").click(function(){

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

});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM