如何使用jQuery选择文本选择中的选项

时间:2011-05-13 18:04:14

标签: jquery

如何使用jQuery在文本选择中设置选项?以下作品

$("#selectID option:contains('optionText')").attr("selected", true);

是否有更简单/更短的方式?

实施例

<select id="fruit">
    <option value="">--select--</option>
    <option value="1">apple</option>
    <option value="2">pineapple</option>
    <option value="3">orange</option>
<select>
<br>
<button>apple</button>
<button>orange</button>
<button>pineapple</button>

$(function() {
    $("button").click(function() {
        $("#fruit option:contains('" + $(this).text() + "')").attr("selected", true);
    })
})

Demo

修改

上面使用Contains发布的版本有一个错误。由于Contains也会匹配部分字符串(例如apple会匹配菠萝),它可以选择不正确的选项。

// Doesn't work in FF4, IE9 using jQuery 1.4.4
$('#fruit').val('apple'); // Doesn't work in FF4, IE9 using jQuery 1.4.4

// Doesn't work either in FF4, IE9 using jQuery 1.4.4
$('#fruit option[text="apple"]').attr("selected", true);

// This works
$("#fruit").children("option[text='apple']").attr("selected", true);

编辑 2012年2月14日

// The above doesn't work in jQuery 1.7.1

// Using even more verbose version [Demo][2]

var buttonText = $(this).text();

$("#fruit option:contains('" + buttonText + "')")
    .filter(function(i){
        return $(this).text() === buttonText;
    })
    .attr("selected", true)

3 个答案:

答案 0 :(得分:3)

你应该可以这样做:

$('#fruit').val('apple');

实际上,在JQuery的NEWER版本中,这不起作用,你是对的。我唯一能想到的是:

$('#fruit option[text="apple"]').attr("selected","selected");

这比你的还要好吗? ;)

答案 1 :(得分:0)

// Work in FF4, IE9 using jQuery 1.4.4 but has a bug (see original post)
$("#selectID option:contains('optionText')").attr("selected", true);

// Doesn't work in FF4, IE9 using jQuery 1.4.4
$('#fruit').val('apple'); // Doesn't work in FF4, IE9 using jQuery 1.4.4

// Doesn't work either in FF4, IE9 using jQuery 1.4.4
$('#fruit option[text="apple"]').attr("selected", true);

// This works
$("#fruit").children("option[text='apple']").attr("selected", true);

Demo

编辑 2012年2月14日

// The above doesn't work in jQuery 1.7.1

// Using even more verbose version [Demo][2]

var buttonText = $(this).text();

$("#fruit option:contains('" + buttonText + "')")
    .filter(function(i){
        return $(this).text() === buttonText;
    })
    .attr("selected", true)

答案 2 :(得分:-1)

可以这样实现:

<select id="fruit">
<option value="">--select--</option>
<option value="1">apple</option>
<option value="2">orange</option>
<select>
<br>
<button data-id="1">apple</button>
<button data-id="2">orange</button>

JS

$(function() {
    $("button").click(function() {
         $("#fruit").val($(this).data('id'));
    });
});

这只是一种可行的方式。您还可以将选项值设置为“apple”和“orange”,然后使用以下js代替。

$(function() {
    $("button").click(function() {
         $("#fruit").val($(this).text());
    });
});
相关问题