jQuery, use ~ as a part of id - how?

隐身守侯 提交于 2019-12-23 09:53:45

问题


In my application I have a form, which elements are named using a certain convention, i.e. they are paths, the parts of which are separated using the ~ sign.

Now I need to access one of them in jQuery by id, but I fail. Apparently, jQuery treats it as the #prev ~ sibling thing.

Is there a way I can sort of escape the ~ sign in the jQuery function?

Here is an example of what my code looks like:

<select id="a~b~c">
  <option value='1'>one</opiton>
</select>

<script>
  $("#a~b~c").change(function(){
    alert('a');
  });
</script>

回答1:


try this

  $("#a\\~b\\~c").change(function(){
    alert('a');
  });



回答2:


There is an answer to that in the official jQuery FAQ.

You need to escape it with \\.




回答3:


You can use \\ http://api.jquery.com/category/selectors/

$('#a\\~b\\~c')

Or, if escaping is problematic you can use: http://api.jquery.com/attribute-equals-selector/

$('[id="a~b~c"]')

Fiddle Demo




回答4:


The escape character in jQuery is two backslahses, \\, so try this:

$("#a\\~b\\~c").change(function(){    
    alert('a');
});

Fiddle to show it working

Further reading on jQuery selectors: http://api.jquery.com/category/selectors/



来源:https://stackoverflow.com/questions/8226331/jquery-use-as-a-part-of-id-how

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