如何使用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);
})
})
EDIT
張貼以上使用包含有一個錯誤的版本。由於Contains也會匹配部分字符串(例如,蘋果會匹配菠蘿),因此可以選擇不正確的選項。
// 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)
爲什麼你想要的東西更短?這看起來很好! – 2011-05-13 18:06:23
實際上,當在一個頁面上碰到這個時,幾個輸入(type = text)以及選擇被選中,然後使用像elems.val(someCond?newValue:「」)這樣的設置進行設置。只要newValue是選擇的值,它對於輸入和選擇都可以正常工作。在某些情況下,選擇需要使用文本進行選擇。我試圖看看是否有一種通用的方法,以便腳本不必添加另一個如果確定elem是輸入還是選擇。 – 2011-05-13 18:11:30
發佈的版本有一個bug和$('#fruit選項[text =「apple」]')。attr(「selected」,「selected」);也不起作用。更新了問題。 – 2011-05-13 21:23:34