簡體   English   中英

使用基於文本的jQuery選擇選項

[英]Select option using Jquery base on text

<select>
  <option value="something else">James</option>
  <option value="something else">John</option>
</select>

由於某些原因,我可以執行$('select').val('something else')因為value屬性用於其他內容。 為了避免弄亂當前的工作內容,如何根據文本值選擇元素? 說我已經有了JamesJohn的價值。

 $("select option").filter(function() { return $(this).text() == 'John'; }).prop('selected', true) 
 <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> 

使用.filter()

描述:將匹配元素的集合減少為與選擇器匹配或通過功能測試的元素。

您可以使用以下

 $("#yourdropdownid option:selected").text();

這將為您提供文字

$('select').find('option[value="something else"]').prop("selected", true)

嘗試$("select :selected").text();

使用contains可以通過這樣的文本選擇選項。

小提琴演示

堆棧示例:

 $(function() { var text = "John"; $("select option:contains(" + text + ")").attr('selected', 'selected'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <select> <option value="something else">James</option> <option value="something else">John</option> </select> 

 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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM