Jquery get element not working when id contains comma

可紊 提交于 2021-02-04 20:00:35

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!