我有一个 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/