克隆两次jQuery按钮,让他们两个都完成相同的任务

时间:2018-12-10 09:08:01

标签: javascript jquery html

我有一个希望在jquery中克隆的按钮,这样我就可以拥有两个按钮,使用这两个按钮来完成相同的任务,但是当我运行此代码时,只有一个按钮实际起作用,而另一个则不起作用。
我已经尝试将true用作参数,但仍然无法正常工作 任何帮助将不胜感激

Programming Finished
Verify Started
target halted due to breakpoint, current mode: Thread 
xPSR: 0x61000000 pc: 0x2000002e msp: 0x200073fc
[Done] Uploaded the sketch: GetStarted.ino
jQuery(function($) {
  var $button = $('#addEvent'),
    $row = $('.newEvent').clone();

  $button.click(function() {
    $row.clone().insertBefore($button);
  });
});


jQuery(function($) {
  var $button = $('#newPupil'),
    $row = $('.newParticipant').clone();

  $button.click(function() {
    $row.clone().insertBefore($button);
  });
});

1 个答案:

答案 0 :(得分:1)

属性 id 在文档中必须是唯一的,请改用 class 。要附加动态创建的元素,请使用on()

尝试以下方式:

jQuery(function($){
  var $button1 = $('#addEvent'),
  $row1 = $('.newEvent').clone();
  $button1.click(function(){
    $row1.clone().insertBefore($button1);
  });
  
  var $row2 = $('.newParticipant').clone();
  $('body').on('click', '.newPupil', function(){
    $row2.clone().insertBefore(this);
  });
  
});
<div class="newEvent">
  <fieldset id="ResultSheet">
      <legend>Add Event</legend>
          Event: <br>
      <select name="Events" id="Events">
          <option disabled selected value> --SELECT AN OPTION BELOW-- </option>
          <option value="100 Metres">100 Metres</option>
          <option value="200 Metres">200 Metres</option>
          <option value="300 Metres">300 Metres</option>
          <option value="400 Metres">400 Metres</option>
          <option value="800 Metres">800 Metres</option>
          <option value="1500 Metres">1500 Metres</option>
          <option value="400 Metres">400 Metres</option>
          <option value="Hurdels">Hurdels</option>
          <option value="Shot Put">Shot Put</option>
          <option value="Discus">Discus</option>
          <option value="Javelin">Javelin</option>
          <option value="Long Jump">Long Jump</option>
          <option value="High Jump">High Jump</option>
          <option value="Triple Jump">Triple Jump</option>
          <option value="4x100 Metres Relay">4x100 Metres relay</option>
      </select>

      <div class="newParticipant"> 
          <br>
          First name: <input type="text" name="fisrtName">
          Last Name: <input type="text" name="lastName">
      </div>
      <input type="button" class="newPupil" name="newPupil" value="New participant"> 
  </fieldset>
</div>
<input type="button" id="addEvent" name="addEvent" value="Add Event" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<button value="Refresh Page" onClick="refreshPage()">REFRESH</button>
<script src="newButtons.js"></script>