问题是由于 HTML 实体造成的;“ <
”被浏览器视为“ <
”。
bobince 提供的例子也是如此;请注意,以下内容不适用于 Win + FF3 上的 jQuery 1.32:
var select= document.getElementById('SomeDropdown');
for (var i= select.options.length; i-->0;) {
if (select.options[i].value=="a'b]<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]<p>");
var select= document.getElementById('SomeDropdown');
for (var i= select.options.length; i-->0;) {
if (select.options[i].value == srcValue) {
alert('found it');
}
}
现在,您正在搜索的输入值与选择元素的值完全匹配。
这也可以使用 jQuery 方法编写:
var srcValue = html_entity_decode("a'b]<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]<p>");