-1

每次单击时我都有一个按钮,将添加一个新的选择输入。但我也希望更改选择的 ID 和名称。我的代码是:

<section>
  <div class="container">
   <select id="myId_1" name="myName_1">
     <option value="1">1</option>
     <option value="2">2</option>
   </select>
  </div>
</section>
<button type="button" id="myBtn">add</button>

$(document).ready(function () {
    $('#myBtn').click(function(){
      var addEvent = $('.container').html();
      var addEventCell = $('<div class="container">'+addEvent+'</div>');
      $('section').append(addEventCell);
    });
  });

但我的代码只是复制了选择的 ID 和名称。我希望它更改为 myId_2、myName_2、myId_3、myName_3 等等。

我是 JavaScript 新手。对你们来说可能很容易。感谢帮助 !

4

2 回答 2

0
  $(document).ready(function () {
    $('#myBtn').click(function(){
      var addEvent = $('.container:last').html();
      var addEventCell = $('<div class="container">'+addEvent+'</div>');
      var select = $('select', addEventCell);
      var oldId = select.attr('id');
      var newId = oldId.split('_')[0] + '_' + (parseInt(oldId.split('_')[1]) + 1);
      select.attr('id', newId).attr('name', newId);
      $('section').append(addEventCell);
    });
  });​

http://jsfiddle.net/QVYhu/

于 2012-07-13T06:32:46.533 回答
0

这是在这里工作的 JSFiddle的链接。它可能对你有用

$(document).ready(function () {
    $('#myBtn').click(function(){
      var addEvent = $('.container').html();

      var selectid = $('section :last-child select').attr('id'); 
      var selectname = $('section :last-child select').attr('name'); 

      var tempId = parseInt(selectid.split('_')[1])+1; 
      var tempName = parseInt(selectname.split('_')[1])+1; 
      var addEventCell = $('<div class="container">'+addEvent+'</div>');

      var newId =  selectid.split('_')[0]+"_"+tempId; 
      var newName = selectname.split('_')[0]+"_"+tempName ;

      var select = $('select', addEventCell);
      select.attr('id', newId).attr('name', newName);      

      $('section').append(addEventCell);
    });
  });​
于 2012-07-13T06:57:40.133 回答