追加元素,两次追加

时间:2015-12-05 04:02:07

标签: javascript jquery dom

$('label[id="p-n-from"]').on('click',function() {
    var fromele = $('<div id="p-n-from-'+ifrom+'" class="input-control text"  data-role="input"><span class="mif-location prepend-icon"></span><input id="from['+ifrom+']" placeholder =" Enter Pick Up Location"  type="text" required></div>');
    $(fromDiv).append(fromele);
    return false;           
 }); 

<div class="col-md-6 ">
  <label class="input-control ">From</label>
  <div id="from-div">
    <div id="p-n-from-1" class="input-control text" data-role="input">
      <span class="mif-location prepend-icon"></span>
      <input id="from[0]" placeholder="Enter pickup " type="text" required>
    </div>
  </div>
  <div id="" class="col-md-6 ">
    <label id="p-n-from" class="input-control">
      <button class="button mini-button cycle-button mif-plus fg-green"></button>Add More</label>
  </div>
</div>
<div class="col-md-6 ">
  <div id="to-div">
    <label class="input-control ">To</label>
    <div id="p-n-to-1" class="input-control text" data-role="input">
      <span class="mif-location prepend-icon"></span>
      <input id="to[0]" placeholder="Enter drop location" type="text" required>
    </div>
  </div>

</div>

这个简单的脚本是两次添加输入框,尽管大多数表单都有动态添加的元素。

我无法弄清楚为什么这个会被添加两次。我尝试了Appending a DOM element twice (jQuery)

的建议

但它没有帮助。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

如果您只使用div,请添加inputs,试试这个:

1 - 在你的html中添加一个div

<div id='IdYourDiv'></div>

2 - 配置脚本

&#13;
&#13;
var fromele = "<input type='text' id='input1'/><br><input type='text' id='input2'/>";
$('#IdYourDiv').html(fromele);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

$('label[id="p-n-from"]).unbind();

将它放在触发器之前帮助了。