JQuery selector problem in Internet Explorer

2019-07-18 06:18发布

I have a jquery selector that looks like:

var val = "John's cars";
$('#subject input[value="'+val+'"]')

This works just fine in Firefox, Chrome, Internet Explorer 8, but not in IE 6 or IE7. The problem is the ' in the text search for. Someone has any idea how to work around this problem except to loop through all inputs in question and do a string compare?

3条回答
聊天终结者
2楼-- · 2019-07-18 06:51

Try this:

var val = "John's cars";
$('#subject input').filter(function() {
    return this.value == val;
});
查看更多
Emotional °昔
3楼-- · 2019-07-18 07:00

Try escaping the ' with a backslash

var val = "John\'s cars";
$('#subject input[value="'+val+'"]')

from jQuery

Special characters in selectors

If you wish to use any of the meta-characters described above as a literal part of a name, you must escape the character with a backslash (). Since Javascript uses the backslash for escape sequences in string literals, you must use two backslashes (\) in string literals so that a single backslash will be put into the string.

Example:

"#foo\\:bar"
"#foo\\[bar\\]"
"#foo\\.bar"

The full list of characters that need to be escaped: #;&,.+*~':"!^$[]()=>|/

EDIT:

since the value is in a string literal, it needs to be double-escaped. So this works

var val = "John\\'s cars";
$('#subject input[value="'+val+'"]')

Thanks to bobince for pointing it out.

查看更多
我只想做你的唯一
4楼-- · 2019-07-18 07:05

I bet it's the apostrophe in the search value - try escaping it using

"John\'s cars"
查看更多
登录 后发表回答