jQuery로 텍스트 콘텐츠로 옵션 선택
jquery를 사용하여 쿼리 문자열을 통해 전달 된 항목에 드롭 다운 상자를 설정하고 싶습니다.
"TEXT"값이 쿼리 문자열의 특정 매개 변수와 같도록 선택한 속성을 옵션에 추가하는 방법은 무엇입니까?
$(document).ready(function() {
var cat = $.jqURL.get('category');
if (cat != null) {
cat = $.URLDecode(cat);
var $dd = $('#cbCategory');
var $options = $('option', $dd);
$options.each(function() {
if ($(this).text() == cat)
$(this).select(); // This is where my problem is
});
};
});
이것을 교체하십시오 :
var cat = $.jqURL.get('category');
var $dd = $('#cbCategory');
var $options = $('option', $dd);
$options.each(function() {
if ($(this).text() == cat)
$(this).select(); // This is where my problem is
});
이것으로 :
$('#cbCategory').val(cat);
val()
선택 목록을 호출 하면 해당 값이있는 옵션이 자동으로 선택됩니다.
이 질문이 너무 오래되었다는 것을 알고 있지만 여전히이 접근 방식이 더 깨끗할 것이라고 생각합니다.
cat = $.URLDecode(cat);
$('#cbCategory option:contains("' + cat + '")').prop('selected', true);
이 경우를 사용하여 전체 옵션을 검토 할 필요가 없습니다 each()
. 그 당시에 prop()
는 jQuery의 이전 버전에서 attr()
.
최신 정보
contains
여러 옵션을 찾을 수 있기 때문에 사용할 때 확실 해야합니다. 내부 문자열이 cat
일치하려는 옵션과 다른 옵션의 하위 문자열과 일치하는 경우입니다 .
그런 다음 다음을 사용해야합니다.
cat = $.URLDecode(cat);
$('#cbCategory option')
.filter(function(index) { return $(this).text() === cat; })
.prop('selected', true);
귀하의 경우 <option>
요소가없는 value
속성을, 당신은 사용할 수 있습니다 .val
:
$selectElement.val("text_you're_looking_for")
그러나 <option>
요소에 값 속성이 있거나 나중에 수행 될 수있는 .val
경우 가능할 때마다 value
텍스트 콘텐츠 대신 속성으로 옵션을 선택 하기 때문에 작동하지 않습니다 . 옵션에 value
속성 이있는 경우 텍스트 콘텐츠로 옵션을 선택하는 기본 제공 jQuery 메서드가 없으므로 간단한 플러그인으로 직접 추가해야합니다.
/*
Source: https://stackoverflow.com/a/16887276/1709587
Usage instructions:
Call
jQuery('#mySelectElement').selectOptionWithText('target_text');
to select the <option> element from within #mySelectElement whose text content
is 'target_text' (or do nothing if no such <option> element exists).
*/
jQuery.fn.selectOptionWithText = function selectOptionWithText(targetText) {
return this.each(function () {
var $selectElement, $options, $targetOption;
$selectElement = jQuery(this);
$options = $selectElement.find('option');
$targetOption = $options.filter(
function () {return jQuery(this).text() == targetText}
);
// We use `.prop` if it's available (which it should be for any jQuery
// versions above and including 1.6), and fall back on `.attr` (which
// was used for changing DOM properties in pre-1.6) otherwise.
if ($targetOption.prop) {
$targetOption.prop('selected', true);
}
else {
$targetOption.attr('selected', 'true');
}
});
}
페이지에 jQuery를 추가 한 후이 플러그인을 어딘가에 포함시킨 다음
jQuery('#someSelectElement').selectOptionWithText('Some Target Text');
to select options.
The plugin method uses filter
to pick out only the option
matching the targetText, and selects it using either .attr
or .prop
, depending upon jQuery version (see .prop() vs .attr() for explanation).
Here's a JSFiddle you can use to play with all three answers given to this question, which demonstrates that this one is the only one to reliably work: http://jsfiddle.net/3cLm5/1/
참고URL : https://stackoverflow.com/questions/1009740/selecting-option-by-text-content-with-jquery
'Program Tip' 카테고리의 다른 글
C # Winforms의 레이블에 힌트 또는 도구 설명을 추가하려면 어떻게해야합니까? (0) | 2020.10.15 |
---|---|
터미널을 사용하여 실 버전을 업그레이드하는 방법은 무엇입니까? (0) | 2020.10.15 |
Git 버전 해시를 자동으로 인쇄하도록 C 코드를 얻으려면 어떻게해야합니까? (0) | 2020.10.15 |
Android : Spinner 위젯의 텍스트 색상 속성은 어디에 숨어 있습니까? (0) | 2020.10.15 |
동일한 컨트롤러에서 동일한 작업 이름을 가진 GET 및 POST 메서드 (0) | 2020.10.15 |