当id包含逗号时,Jquery get元素不起作用



当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!');
  }
});

您需要用两个反斜杠转义逗号:

var str = "#1\,3";

jsFiddle示例

请参阅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/

使用任何元字符(例如!"#$%&'()*+,./:;<=>?@[]^{|}~)作为名称的文字部分,它必须用两个反斜杠转义:\\

选择元素的另一种方法是attribute equals选择器:

$(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>

最新更新