在选择字段中查找并替换选项

时间:2014-02-14 07:46:32

标签: javascript jquery

我正在尝试查找并替换选择框中的选项,
我正在使用这段代码,但这不起作用请帮帮我!

$(".select" option).each(function() {
    if $(this).val() == "Unknown" {
        $(this).val().replaceWith( "---------" );
    }
});

4 个答案:

答案 0 :(得分:2)

您需要将option放在选择器中并使用val()的setter版本:

$(".select option").each(function() {
    if $(this).val() == "Unknown" {
        $(this).val("---------");
    }
});

答案 1 :(得分:1)

这样的事情也会起作用:

$('#mySelect option:contains("Unknown")').text("---------");

http://jsfiddle.net/tKP68/

答案 2 :(得分:0)

试试这个......

$(".select option").each(function() {
    if $(this).val() == "Unknown" {
        $(this).val().replaceWith( "---------" );
    }
});

答案 3 :(得分:0)

取决于您想要达到的目标:

$('select option').each(function () {
    if (this.value === 'Unknown') { // You should always use === instead of ==
        this.value = '---------'; // Change value
        this.innerText = '---------'; // Change the option's text
    }
});
相关问题