每次单击时都会有一个按钮,将添加一个新的选择输入。但我希望选择的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);
});
});
但我的代码只是重复了select的id和名称。我希望它更改为myId_2,myName_2,myId_3,myName_3等。
我是javascript的新手。对你们来说这很容易。谢谢你的帮助!
答案 0 :(得分: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);
});
});
答案 1 :(得分: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);
});
});