【问题标题】:Cloned jquery elements are triggering events to parent <div> instead of child<div>?克隆的 jquery 元素正在触发事件到父 <div> 而不是子 <div>?
【发布时间】:2019-05-01 12:08:50
【问题描述】:

我正在构建一个工具,我在其中插入了一些动态输入字段以获取用户的输入。我从代码中克隆了一些 div 来制作不同的部分。我的 div 已成功克隆,但附加到父 div 的事件总是被触发到父 div,即使我单击子 div 事件。

我已设置$("#main").clone(true).insertAfter("#main"); 更改其默认布尔值以触发事件。我不知道该怎么做才能使它在每个克隆的 div 而不是父 div 上工作。

这是我的输入表单

<form name="add_name" id="add_name">  
        <div class="table-responsive">  
              <table class="table table-bordered" id="dynamic_field">  
                      <tr>  
                             <td><input class="typeahead form-control" type="text" placeholder="Enter Description"></td>
                             <td> <?php echo form_dropdown('id',$unit_name, '', 'class="form-control"');?> </td>
                             <td> <input type="quantity" class="form-control" id="quantity" placeholder="Enter Quantity"></td>
                             <td><input type="price" class="form-control" id="price" placeholder="Enter Rate"></td>
                             <td><label for="total" >Price:</label>
                             <td> <a href="#"> <span class="glyphicon glyphicon-plus" name="add" id="add"></span></td>
                      </tr> 
               </table>  
               <input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />  
         </div>  
</form>  

这是我的 javascript 函数:

这个是克隆div和相关事件

<script>
    $("#btnAdd").click(function() {
         $("#main").clone(true).insertAfter("#main");
    });
</script>

这是生成动态输入字段并被克隆的功能

$(document).ready(function(){  
      var i=1;  
      $('#add').click(function(){  
           i++;  
           $('#dynamic_field').append('<tr id="row'+i+'"> <td><input class="typeahead form-control" type="text" placeholder="Enter Description"></td>\n\
  <td> <input type="quantity" class="form-control" id="quantity" placeholder="Enter Quantity"></td>\n\
  \n\
<td><input type="price" class="form-control" id="price" placeholder="Enter Rate"></td>\n\
 <td><label for="total" >Price:</label>\n\
<td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');  
      });
});

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    您正在使用 id #main 进行克隆。从文档中,

    使用 .clone() 具有生成具有重复 id 属性的元素的副作用,这些属性应该是唯一的。在可能的情况下,建议避免使用此属性克隆元素或使用类属性作为标识符。

    这就是为什么它总是在第一个 div 上触发。因此,从新创建的 div 中删除 id 元素并尝试使用class

    另一种方法,您可以克隆它$("#main").clone() 并将onclick 事件用于动态元素而不是click 事件。

    【讨论】:

    • 我尝试按如下方式使用点击事件,但在任何 div 中都不再触发事件:
    • 再次,您只使用id
    • 你能告诉我如何用 class 替换 id,因为我做的方式没有任何区别。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多