当id包含逗号时,为什么jquery选择器不起作用? 见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!');
}
});
答案 0 :(得分:2)
你需要用两个反斜杠转义逗号:
var str = "#1\\,3";
<强> jsFiddle example 强>
请参阅https://learn.jquery.com/using-jquery-core/faq/how-do-i-select-an-element-by-an-id-that-has-characters-used-in-css-notation/和https://api.jquery.com/category/selectors/
使用任何元字符(例如
!"#$%&'()*+,./:;<=>?@[\]^
{|}〜)作为名称的文字部分,必须 用两个反斜杠转义:\\
答案 1 :(得分:0)
选择元素的另一种方法是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>