PS:之前有两个答案,我刷新了这个页面,答案消失了,发生了什么?
html
<table>
<tr class='test_tr'>
<td>
<select class='test_select'>
<option value=1>test1</option>
<option value=2>test2</option>
<option value=3>test3</option>
</select>
</td>
<td><a href="#" class='test_clone'>clone</a></td>
</tr>
JS
$(document).ready(function(){
$('select.test_select').selectmenu();
$('.test_clone').click(function(){
var tp = $(this).parents('.test_tr');
var new_tr = tp.clone(true);
new_tr.insertAfter(tp);
tr_func(new_tr);
})
});
function tr_func(new_tr){
$('.test_select',new_tr).selectmenu();
}
单击克隆按钮并单击新选择后,它始终会影响第一个。 有什么建议吗?谢谢!
答案 0 :(得分:1)
这个问题有一些有趣的方面:
克隆行时,所有具有id
属性的项目也将被克隆,导致两个元素具有相同的#ID
;这不好。可以通过创建每次单击按钮时克隆的原始样本行来解决,然后在使用之前必须“装饰”(即应用.selectmenu()
并单击处理程序)。
克隆<select>
时,它不会保留所选选项。您必须保存selectedIndex
属性并将其应用于克隆版本。
这两个问题都解决了这个问题:
$(document).ready(function() {
// keep reference to the sample row
var sample = $('.test_tr.sample');
// click handler for the clone button
function cloneRow()
{
var parentRow = $(this).parents('.test_tr'),
selectedOption = parentRow.find('.test_select').prop('selectedIndex');
setupRow(newRow().insertAfter(parentRow), selectedOption);
}
// decorates the new row and sets the correct selected option before applying
// selectmenu()
function setupRow(row, selectedOption)
{
row
.find('.test_select')
.prop('selectedIndex', selectedOption || 0)
.selectmenu()
.end()
.find('.test_clone')
.click(cloneRow)
.end()
}
// helper function that clones the sample and shows it before handing it over
// to other code.
function newRow()
{
return sample.clone().show();
}
// setup the first row
setupRow(newRow().appendTo('table'));
});
答案 1 :(得分:1)
这是我提出的,更少的代码,没有外部功能。
$('select.test_select').selectmenu();
$('.test_clone').on('click', function(){
var $row = $(this).parents('.test_tr'); //get parent tr row
var $select = $row.find('.test_select'); //get select box
var selectedIndex = ($select.prop('selectedIndex') || 0); //copy current selectedIndex
$select = $select.clone(false); //clone select box, withDataAndEvents = false
$select.prop('selectedIndex', selectedIndex); //apply selectedIndex
$select.removeAttr('id'); //remove id as selectmenu will apply the correct id
var $tbody = $row.parent();
var $newrow = $row.clone(true); //clone row, withDataAndEvents = true
$('td:first', $newrow).empty(); //empty the first td
$('td:first', $newrow).append($select); //append cloned select box
$tbody.append($newrow); //append row to table
$('.test_select', $newrow).selectmenu(); //apply jquery.ui.selectmenu
});
答案 2 :(得分:0)
生成的所有克隆选择框都具有相同的ID。这是一个无效的DOM结构的例子。
可能是导致第一个选择菜单打开的原因,点击任何一个菜单。
答案 3 :(得分:0)
必须在执行clone()
时,它也会克隆菜单小部件元素,因此会产生奇怪的行为。我尝试更新你的代码以从模板元素克隆它并且它起作用。