выход значения селектора jQuery

Не уверен, что ты этого хочешь. Это выбирает первый входной дочерний внутренний #root.

#root input:nth-of-type(1) { 
    background: red;
}

Или вы хотите выбрать вход со значением «Имя»?

#root input[value="First Name"] {
    background: red;
}
54
задан Keavon 19 May 2014 в 06:01
поделиться

3 ответа

I don't think you can. It should be:

#SomeDropdown >option[value='a\'b]<p>']

And this does work as a CSS selector (in modern browsers). Expressed in a JavaScript string literal you would naturally need another round of escaping:

$("#SomeDropdown >option[value='a\\'b]<p>']")

But this doesn't work in jQuery because its selector parser is not completely standards-compliant. It uses this regex to parse the value part of an [attr=value] condition:

(['"]*)(.*?)\3|)\s*\]

\3 being the group containing the opening quotes, which weirdly are allowed to be multiple opening quotes, or no opening quotes at all. The .*? then can parse any character, including quotes until it hits the first ‘]’ character, ending the match. There is no provision for backslash-escaping CSS special characters, so you can't match an arbitrary string value in jQuery.

(Once again, regex parsers lose.)

But the good news is you don't have to rely on jQuery selectors; there are perfectly good DOM methods you can use, in particular HTMLSelectElement.options:

var select= document.getElementById('SomeDropdown');
for (var i= select.options.length; i-->0;) {
    if (select.options[i].value=="a'b]<p>") {
        // do something with option
}   }

This is many times simpler and faster than asking jQuery to laboriously parse and implement your selector, and you can use any value string you like without having to worry about escaping special characters.

38
ответ дан bobince 7 November 2019 в 07:55
поделиться

Проблема связана с сущностями HTML; « & lt; » воспринимается браузером как « <».

То же самое можно сказать о примере, представленном bobince; обратите внимание, что следующее не работает с jQuery 1.32 в Win + FF3:

var select= document.getElementById('SomeDropdown');
for (var i= select.options.length; i-->0;) {
    if (select.options[i].value=="a'b]&lt;p>") {
        alert('found it');
    }   
}

Однако, изменение сущности на литерал действительно найдет желаемое значение:

var select= document.getElementById('SomeDropdown');
for (var i= select.options.length; i-->0;) {
    if (select.options[i].value=="a'b]<p>") {
        alert('found it');
    }   
}

Конечно, здесь есть проблема, так как значение, которое вы указываете не точное значение, которое вы ищете. Это также можно исправить, добавив вспомогательную функцию:

function html_entity_decode(str) {
    var decoder = document.createElement('textarea');
    decoder.innerHTML = str;
    return decoder.value;
}

Теперь все вместе:

var srcValue = html_entity_decode("a'b]&lt;p>");
var select= document.getElementById('SomeDropdown');
for (var i= select.options.length; i-->0;) {
    if (select.options[i].value == srcValue) {
        alert('found it');
    }   
}

В любом случае, искомое входное значение в точности совпадает со значением элемента select.

Это также может быть написаны с использованием методов jQuery:

var srcValue = html_entity_decode("a'b]&lt;p>");
$($('#SomeDropdown').attr('options')).each(function() {
    if (this.value == srcValue)
    {
        $(this).remove();
    }
});

И, наконец, как плагин, поскольку их так легко сделать:

jQuery.fn.removeByValue = function( val )
{
    var decoder = document.createElement('textarea');
    decoder.innerHTML = val;    
    var srcValue = decoder.value;

    $( $(this)[0].options ).each(function() {
        if (this.value == srcValue) {
            $(this).remove();
        }
    });

    return this;
};

$('#SomeDropdown').removeByValue("a'b]&lt;p>");
2
ответ дан ken 7 November 2019 в 07:55
поделиться

Я использую эту функцию, чтобы избежать селекторов jquery. Она избегает практически всего сомнительного, но может быть слишком агрессивным.

function escapeStr(str) 
{
    if (str)
        return str.replace(/([ #;?%&,.+*~\':"!^$[\]()=>|\/@])/g,'\\$1');      

    return str;
}
51
ответ дан 7 November 2019 в 07:55
поделиться
Другие вопросы по тегам:

Похожие вопросы: