<select>
<option value="something else">James</option>
<option value="something else">John</option>
</select>
出于某种原因,我可以$('select').val('something else')
,因为value属性用于其他内容。为避免弄乱当前的工作内容,如何根据文本值选择元素?说我已经获得了值James
和John
。
答案 0 :(得分:2)
$("select option").filter(function() {
return $(this).text() == 'John';
}).prop('selected', true)
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value="something else">James</option>
<option value="something else">John</option>
</select>
&#13;
描述:将匹配元素集合减少到与选择器匹配的元素或通过函数测试。
答案 1 :(得分:1)
您可以使用以下
$("#yourdropdownid option:selected").text();
这将为您提供文字
答案 2 :(得分:1)
$('select').find('option[value="something else"]').prop("selected", true)
答案 3 :(得分:1)
尝试使用$("select :selected").text();
答案 4 :(得分:1)
使用<?php
$myactiveli = $_GET['con'];
?>
<html>
<body>
<div class="container">
<ul class="nav navbar-nav ct-navbar--fadeIn">
<li <?php if($myactiveli==1) { echo 'class="active"'; } ?> >
<a href="index.php?con=1">HEM</a>
</li>
<li <?php if($myactiveli==3) { echo 'class="active"'; } ?>><a href="index.php?con=3">OM OSS</a></li>
</ul>
<div class="clear"></div>
</div>
</body>
</html>
按文字选择选项。
堆栈示例:
contains
&#13;
$(function() {
var text = "John";
$("select option:contains(" + text + ")").attr('selected', 'selected');
});
&#13;
答案 5 :(得分:0)
var selectText = function(elem, text) {
if (elem && text) {
elem.find('option').each(function() {
var that = $(this);
if (that.text() == text) {
that.attr('selected', 'selected');
}
});
}
}
selectText($('#target'), 'John');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="target">
<option value="something else">James</option>
<option value="something else">John</option>
</select>