jQuery:如何访问 id 中带有加号 (+) 的元素

标签 jquery variables

我有一个 jQuery 循环,可以将多行附加到表中。行数可以在运行时更改,因此行 ID 是动态生成的。

$("#tableBody")
    .append($("<tr>")
        .attr('id','row-icon' + currentID)...

稍后,我需要访问这些添加的行。然而,当 currentID 的值为其中有一个“+”符号 - 当我尝试访问行元素时,出现“未定义”错误。

例如,下面的行在 currentID 时有效是“1” - 但当 ID 是“vm+1”时失败。

var testID = $("#row-icon" + currentID).attr("id");

我是否缺少一个简单的解决方案来“转义”额外的“+”符号?

工作示例 here .

编辑:我应该注意,ID 是由第 3 方发送的 - 因此我无法控制删除“+”符号。

最佳答案

它不起作用,因为 + 符号是 jQuery 选择器中所谓的元字符,如 explained in the documentation 。您应该使用 2 个反斜杠对其进行转义:

To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[\]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\. For example, an element with id="foo.bar", can use the selector $("#foo\\.bar"). The W3C CSS specification contains the complete set of rules regarding valid CSS selectors. Also useful is the blog entry by Mathias Bynens on CSS character escape sequences for identifiers.

因此,就您而言,您会这样做(请参阅 jsFiddle ):

var test = $("#expand-icon" + currentID.replace(/\+/g, '\\+')).attr("src");
var testID = $("#row-icon" + currentID.replace(/\+/g, '\\+')).attr("id");

关于jQuery:如何访问 id 中带有加号 (+) 的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18211156/

相关文章:

c# - 基于下拉菜单上的选择的 MVC3 锁定文本框

jquery - 根据条件排除点击事件?

javascript - 在 if block 中定义 JavaScript 变量有什么问题?

java - 从另一个按钮的 mouseClicked 方法访问一个按钮?

java - 如何从动态创建的 JTable 中获取值

java - 如何使用 WebDriver 将字符串保存为变量,然后在另一个测试中使用 tis 变量

javascript - 为什么 jQuery 子选择器以父为目标?

java - 打印 AJAX 成功数据?

javascript - 将 Html 存储到数组中,然后将其保存在数据库中并检索该数组 - 显示错误

javascript - 将 Javascript 变量附加到 Jquery AJAX URL