find element with dynamic name using jquery - Quotes problem
I'm searching through my DOM based on the value an option in a select box has.
"searchkey" can be different things, depending on what a user has entered, e.g:
- searchkey = d开发者_Python百科ell'anno
- searcheky = dell"anno
Those options (first one in this case) will break my code below because of the quote. Is there a native jQuery way to solve this?
.uiDialog.find("#var_variantnew_options option[value='"+searchkey+"']")).html()
You’ll need to escape the '
characters, like this: \'
This can be automated as follows:
"foo'bar'baz".replace(/'/g, "\\'"); // "foo\'bar\'baz"
The full code snippet would be:
.uiDialog.find("#var_variantnew_options option[value='" + searchkey.replace(/'/g, "\\'") + "']")).html()
jQuery offers you several ways to do the same thing. Of course you can escape as Mathias suggested, it works. But sometimes it takes less time to just go a different route. Like using a filter function instead:
.UiDialog.find("#var_variantnew_options option").filter(function () {
return this.value==searchkey;
}).html();
try this plugin http://plugins.jquery.com/project/escape
精彩评论