jQuery选择器包含括号 [英] JQuery selector cointains parentheses
问题描述
我的div的ID是从数据库中提取的.这些ID有时包含括号,这会导致JQuery选择器不起作用.我该怎么办?
I have div's with ids that are pulled from a database. These ids sometimes contain parentheses and this causes the JQuery selector to not work. What can I do?
以下是我所谈论的例子:
Here is an example of what I am talking about:
https://jsfiddle.net/2uL7s3ts/1/
var element = 'hello (world)';
$('#' + element).hide();
推荐答案
我不建议使用属性选择器(如其他答案所示),建议切换回本机getElementById
方法.
Rather than using an attribute selector, as the other answer suggests, I would suggest switching back to the native getElementById
method.
$(document.getElementById(element)).hide();
我之所以建议通过属性选择器,是出于性能方面的考虑.属性可以存在于任何元素上,因此当您执行它时,javascript必须扫描上下文中的每个元素以查看它是否具有具有匹配值的属性.
The reason I sugguest this over an attribute selector is for performance reasons. An attribute can exist on any element, so when you perform it, javascript has to scan every element within the context to see if it has the attribute with a matching value.
使用getElementById
(它接受文字ID而不是选择符),将不会进行DOM扫描.
Using getElementById
, which takes a literal id and not a selector, the DOM scan will not happen.
这篇关于jQuery选择器包含括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!