[英]jQuery empty select but not the first option
我在WordPress中使用jQuery AJAX加載兩個下拉列表。 我將AJAX數據作為字符串獲取,我只是將<option>
s附加到我的<select>
字段。 它工作正常。 但每次它都沒有清除之前的追加。 所以它實際上是在添加重復選項。
所以我做了一個更改,我在<select>
字段中添加了empty()
:
jQuery.ajax({
type: 'POST',
url: ajaxurl,
data: {"action": "load_product",
"company_id": company_id
},
success: function (data) {
jQuery('#company-products').empty().append( data );
}
});
但是我默認在選擇字段中有一個空值選項,它只是刪除那個。
<select name="product" id="company-products" class="form-control" required>
<option value=""><?php _e( 'Select a product', 'textdomain' ); ?></option>
</select>
如何附加其他選項,但即使空( value=""
)也不為空。
請注意,我知道我可以從jQuery傳遞空字段,但出於翻譯目的,我無法從那里傳遞它。 所以我想要一個使用jQuery的可靠解決方案,而第一個選項仍然存在。
我甚至嘗試將其更改為:
jQuery('#company-products').not(':first-child').empty();
jQuery('#company-products').append( data );
它沒有用,甚至沒有附加任何東西。 :(
嘗試使用nextAll()
- 刪除空<option>
后的所有元素
var emptyOp = $('#company-products :first-child');
emptyOp.nextAll().remove();
emptyOp.after(data);
您還可以使用許多其他選擇器,
$('#company-products :gt(0)').remove();
$('#company-products').append(data);
要么
$('#company-products :not(:first-child)').remove();
$('#company-products').append(data);
不要使用empty()
只需使用remove()
。
$('#company-products').children('option:not(:first)').remove();
希望這對你有用
如果你只是試着寫怎么辦?
<?php _e( 'Select a product', 'textdomain' ); ?>
從jQuery開始編寫JS變量並傳遞給你的選項?
var selectOption = '<?php _e( 'Select a product', 'textdomain' ); ?>';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.