JQuery selector cointains parentheses

2020-04-18 07:01发布

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();

2条回答
放我归山
2楼-- · 2020-04-18 07:20

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();

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.

Using getElementById, which takes a literal id and not a selector, the DOM scan will not happen.

查看更多
够拽才男人
3楼-- · 2020-04-18 07:29

You can use the attribute selector for ID

$("[id='" + element + "']").hide();

or modify your string selector with a regex to remove the parentheses and spaces

element = element.replace(/(?=[() ])/g, '\\');
$('#' + element).hide();
查看更多
登录 后发表回答