从ajax调用动态创建选项列表时,我想根据选项文本的前几个字符将其中一个选项设置为“已选择”。使用此HTML:
<select id="test">
<option value="bird">123 Bird</option>
<option value="bat">456 Bat</option>
<option value="cat">768 Cat</option>
<option value="dog">890 Dog</option>
</select>
我可以使用将根据VALUE设置所选内容的jQuery
$(document).ready(function () {
$("#test option[value^='ca']").prop('selected', true);
});
但是,我想设置基于TEXT选择的选项,但这不起作用:
$(document).ready(function () {
$("#test option[text^='768']").prop('selected', true);
});
以下是两行演示:http://jsfiddle.net/pfinigan/wzy7f5dr/13/
所以,问题是如何通过文本的第一部分选择选项?
答案 0 :(得分:1)
因为元素的textContent
不是该元素的属性,而是属性,所以不能使用[attribute=value]
选择器;相反,您必须选择相关的元素,然后过滤该元素集合。在这里,我们使用jQuery的filter()
方法:
// selecting the relevant `<option>` elements, and filtering
// that collection:
$('#test option').filter(function(){
// here we retain those elements whose text starts
// with the string of '678' (and discard those
// elements whose text does not start with 768):
return this.textContent.startsWith('768')
// and set the 'selected' property of those retained
// elements to true:
}).prop('selected',true);
$('#test option').filter(function(){
return this.textContent.startsWith('768')
}).prop('selected',true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="test">
<option value="bird">123 Bird</option>
<option value="bat">456 Bat</option>
<option value="cat">768 Cat</option>
<option value="dog">890 Dog</option>
</select>
但是,如果您希望使用纯JavaScript,那么我们可以使用纯JavaScript来实现:
// Create an Array from the iterable Object (a NodeList)
// returned from document.querySelectorAll():
Array.from(document.querySelectorAll('#test option'))
// filtering that Array of <option> elements:
.filter(function(option) {
// 'option' refers to the current <option> of the
// Array of <option> elements over which we're iterating:
// here we retain those whose textContent starts with
// the String '768':
return option.textContent.startsWith('768')
// iterating over the Array returned by Array.prototype.filter():
}).forEach(function(option) {
// option again refers to the current <option>:
// setting the selected property to true:
option.selected = true;
});
Array.from(document.querySelectorAll('#test option')).filter(function(option) {
return option.textContent.startsWith('768')
}).forEach(function(option) {
option.selected = true;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="test">
<option value="bird">123 Bird</option>
<option value="bat">456 Bat</option>
<option value="cat">768 Cat</option>
<option value="dog">890 Dog</option>
</select>