如何在clone()操作期间删除选定的元素 [英] How to remove the selected element during a clone() operation
问题描述
我有一个被克隆的选择框.我想从每个克隆的选择框中删除用户的先前选择.这是执行clone()
的方法:
I have a select box that gets cloned. I want to remove the user's previous selection from each cloned select box. Here is the method that does the clone()
:
function addselect(s){
$('#product_categories > .category_block:last').after(
$('#product_categories > .category_block:last').clone()
);
set_add_delete_links();
return false;
}
function set_add_delete_links(){
$('.remove_cat').show();
$('.add_cat').hide();
$('.add_cat:last').show();
$("#product_categories > .category_block:only-child > .remove_cat").hide();
}
function removeselect(s){
$(s).parent().remove();
set_add_delete_links();
return false;
}
这种方法有效,但不会删除最后选择的内容:
This kinda works but doesn't remove the last selected:
$('#product_categories > .category_block:last option:selected').remove();
这是HTML
<div id="product_categories">
<div class="category_block">
<select name="category_ids[]" id="cat_list">
<option value="">Select Attribute</option>
<option value="1770">Foo0</option>
<option value="1773">Foo1</option>
<option value="1775">Foo2</option>
<option value="1765">Foo3</option>
<option value="1802">Foo4</option>
<option value="1766">Foo5</option>
</select>
<input class="specsinput" type="text" name="specs[]" value="" />
<a href="#" onClick="return removeselect(this);" class="remove_cat"> [-] </a>
<a href="#" onClick="return addselect(this);" class="add_cat"> [+] </a>
</div>
推荐答案
您需要克隆适当的元素,为克隆设置选定的值,然后追加克隆.
You need to clone the proper element, set the selected value for the clone, then append the clone.
function addselect(s){
// Store the block in a variable
var $block = $('#product_categories > .category_block:last');
// Grab the selected value
var theValue = $block.find(':selected').val();
// Clone the block
var $clone = $block.clone();
// Find the selected value in the clone, and remove
$clone.find('option[value=' + theValue + ']').remove();
// Append the clone
$block.after($clone);
set_add_delete_links(); return false;
}
更新:已修改为适合添加到问题中的HTML.
UPDATE: Modified to fit HTML added to question.
请注意,正在克隆选择元素的ID,这意味着您有2个具有相同ID的元素.这是不允许的.您需要删除该ID,或将克隆中的ID更改为其他值.
Please note, the ID of the select element is being cloned, which means you have 2 elements with the same ID. This is not allowed. You'll need to get rid of the ID, or change it in the clone to some other value.
在添加克隆之前,您可以执行以下操作:
You could do something like this before you append the clone:
// Grab the select in the clone
var $select = $clone.find('select');
// Update its ID by concatenating theValue to the current ID
$select.attr('id', $select.attr('id') + theValue);
这篇关于如何在clone()操作期间删除选定的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!