jQuery:处理id属性中的空格 [英] jQuery: dealing with a space in the id attribute

查看:213
本文介绍了jQuery:处理id属性中的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个id为"A B"的元素.以下代码失败:

I have an element with id="A B". The following code fails:

<input type="text" id="A B">
<script>$("#A B").click(function(){alert();});</script>

以下代码不会失败:

<input type="text" id="AB">
<script>$("#AB").click(function(){alert();});</script>

推荐答案

虽然在HTML的ID属性值中保留空格在技术上是无效的(请参阅@ karim79的答案),但实际上您可以使用jQuery选择它.

While it’s technically invalid to have a space in an ID attribute value in HTML (see @karim79’s answer), you can actually select it using jQuery.

请参见 http://mothereffingcssescapes.com/#A%20B :

<script>
  // document.getElementById or similar
  document.getElementById('A B');
  // document.querySelector or similar
  $('#A\\ B');
</script>

jQuery使用类似于Selectors API的语法,因此您可以使用$('#A\\ B');通过id="A B"选择元素.

jQuery uses a Selectors API-like syntax, so you could use $('#A\\ B'); to select the element with id="A B".

要定位CSS中的元素,您可以这样将其转义:

To target the element in CSS, you could escape it like this:

<style>
  #A\ B {
    background: hotpink;
  }
</style>

这篇关于jQuery:处理id属性中的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆