问题
Why does the jquery selector not work when the id contains a comma? See http://jsfiddle.net/sGQas/188/
<div id="1,3">Hello There!</div>
$(document).ready(function () {
var str = "#1,3";
if ($(str).length) {
alert($(str).position().left);
} else {
alert('The element "'+str+'" does not exist on the document!');
}
});
回答1:
You need to escape the comma with two backslashes:
var str = "#1\\,3";
jsFiddle example
See https://learn.jquery.com/using-jquery-core/faq/how-do-i-select-an-element-by-an-id-that-has-characters-used-in-css-notation/ and https://api.jquery.com/category/selectors/
To use any of the meta-characters ( such as
!"#$%&'()*+,./:;<=>?@[\]^
{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\
回答2:
Another way to select the element is attribute-equals-selector:
$(function () {
var str = '[id="1,3"]';
if ($(str).length) {
alert('Text: ' + $(str).text() + ' Left position: ' + $(str).position().left);
} else {
alert('The element "'+ str +'" does not exist on the document!');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="1,3">Hello There!</div>
来源:https://stackoverflow.com/questions/36991611/jquery-get-element-not-working-when-id-contains-comma