2012-07-13 58 views
-1

每次點擊一個按鈕時,都會添加一個新的選擇輸入。但我想要的ID和名稱的選擇改變以及。我的代碼是:在js中點擊一個按鈕增加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的新手。這對你們來說可能很簡單。感謝幫助 !

+1

檢查這個http://stackoverflow.com/questions/3416227/create-dynamic-div-with-unique-ids-jquery它可以幫助你實現你所想。 – TRR 2012-07-13 06:34:52

回答

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); 
    }); 
    });​ 
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/

+0

thx!我測試了它,但似乎沒有奏效。這裏是測試:[鏈接](http://jsfiddle.net/5dyjX/) – 2012-07-13 06:50:55

+0

Ooops,我忘了提高它的價值! http://jsfiddle.net/QVYhu/ – odupont 2012-07-13 08:37:07