jQuery 使用 Space 并通过变量通过 ID 查找元素
jQuery Finding Element By Id With Space And Via Variable
我可以通过id定位一个元素的元素,当id是硬编码的时候加一个class,例如:
var tableId = el.id;
$('#' + tableId).find("[id='Checkout On']").addClass('highlight');
但是,我想将 'Checkout On' 作为变量传递,例如:
var tableId = el.id;
var childEl = col.id;
$('#' + tableId).find("[id=" + childEl + "]").addClass('highlight');
然而这似乎不起作用。
更新:
完全理解 ID 不应该有空格,但这不是我能够解决的问题。
您在使用变量的版本中遗漏了引号:
$('#' + tableId).find("[id='" + childEl + "']").addClass('highlight');
// ------------------------^---------------^
但请注意,其中包含 space 的 id
是 无效的 。来自 the spec:
3.2.5.1 The id
attribute
The id
attribute specifies its element's unique identifier (ID). [DOM]
The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.
(我的重点)
这意味着即使它在一个浏览器上工作,也不能保证它在另一个浏览器上工作,甚至在它工作的那个浏览器的下一个次要版本中也能工作。 (我打赌它会,但没有理由去诱惑这样的事情......)
您不应该在任何 ID 或 class 名称中使用空格。使用 snake_case 或驼峰式大小写:checkout_on
或 checkoutOn
如果您想要 select 具有 ID 的元素,请使用 #...
select 或。这是更好的。像这样:
var tableId = el.id;
var childEl = col.id;
$('#' + tableId).find("#" + childEl ).addClass('highlight');
注意: ID 不能有空格。查看 this 了解更多信息。
我可以通过id定位一个元素的元素,当id是硬编码的时候加一个class,例如:
var tableId = el.id;
$('#' + tableId).find("[id='Checkout On']").addClass('highlight');
但是,我想将 'Checkout On' 作为变量传递,例如:
var tableId = el.id;
var childEl = col.id;
$('#' + tableId).find("[id=" + childEl + "]").addClass('highlight');
然而这似乎不起作用。
更新:
完全理解 ID 不应该有空格,但这不是我能够解决的问题。
您在使用变量的版本中遗漏了引号:
$('#' + tableId).find("[id='" + childEl + "']").addClass('highlight');
// ------------------------^---------------^
但请注意,其中包含 space 的 id
是 无效的 。来自 the spec:
3.2.5.1 The
id
attributeThe
id
attribute specifies its element's unique identifier (ID). [DOM]The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.
(我的重点)
这意味着即使它在一个浏览器上工作,也不能保证它在另一个浏览器上工作,甚至在它工作的那个浏览器的下一个次要版本中也能工作。 (我打赌它会,但没有理由去诱惑这样的事情......)
您不应该在任何 ID 或 class 名称中使用空格。使用 snake_case 或驼峰式大小写:checkout_on
或 checkoutOn
如果您想要 select 具有 ID 的元素,请使用 #...
select 或。这是更好的。像这样:
var tableId = el.id;
var childEl = col.id;
$('#' + tableId).find("#" + childEl ).addClass('highlight');
注意: ID 不能有空格。查看 this 了解更多信息。