jQuery空选择,但不是第一个选项

jQuery empty select but not the first option

本文关键字:第一个 选项 选择 jQuery      更新时间:2023-09-26

我正在WordPress中使用jQuery AJAX加载两个下拉菜单。我将AJAX数据作为一个字符串,并简单地将这些<option>附加到我的<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字段中有一个空值选项,它只是简单地删除了那个选项。

<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' ); ?>

JS变量,并在编写时将选项从jQuery传递给您?

var selectOption = '<?php _e( 'Select a product', 'textdomain' ); ?>';