programing

jQuery로 텍스트 내용별 옵션 선택

codeshow 2023. 10. 24. 21:39
반응형

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);

선택 목록을 호출하면 해당 값을 가진 옵션이 자동으로 선택됩니다.

이 질문이 너무 오래된 질문이라는 것을 알지만, 그래도 이 방법이 더 깔끔할 것 같습니다.

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>원소들이 가지고 있지 않습니다.valueAttribute를 사용하면 다음을 사용할 수 있습니다.

$selectElement.val("text_you're_looking_for")

하지만, 만일 당신이<option>요소들은 가치 속성을 가지고 있거나 미래에 그럴 수도 있습니다. 왜냐하면 가능할 때마다 이것은 작동하지 않을 것이기 때문입니다..val옵션을 선택할 것입니다.value텍스트 내용 대신 속성을 지정합니다.옵션이 다음과 같은 경우 텍스트 내용으로 옵션을 선택하는 기본 제공 jQuery 메서드는 없습니다.value속성에 따라 간단한 플러그인을 추가해야 합니다.

/*
  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');

옵션을 선택합니다.

플러그인 메소드는 다음을 선택하는 데만 사용합니다.option목표와 일치하기텍스트를 입력하고 다음 중 하나를 사용하여 선택합니다..attr아니면.prop, jQuery 버전에 따라 달라집니다(설명은 .prop() vs.attr() 참조).

다음은 이 질문에 주어진 세 가지 답변을 모두 사용하여 플레이할 수 있는 JSFiddle로, 이 답변만이 안정적으로 작동할 수 있음을 보여줍니다. http://jsfiddle.net/3cLm5/1/

언급URL : https://stackoverflow.com/questions/1009740/selecting-option-by-text-content-with-jquery

반응형