[英]Select Element whose ID is attribute in another Element
How do I select an element whose ID is given in an attribute of another element? 如何选择在另一个元素的属性中给出ID的元素?
<div id="_News" class="link active" data-wife="News">News</div>
I want to grab the element with the ID given in data-wife
. 我想用
data-wife
给出的ID来获取元素。 I've tried something like 我已经尝试过类似
$("'#" + $(this).attr("data-wife") + "'").show();
but it looks totally wrong to me (and does not work, of course..). 但这对我来说似乎是完全错误的(当然是行不通的..)。
You're doubling up your quotes. 您正在加倍报价。 You would end up with a selector that was interpreted like this:
您最终将得到一个解释如下的选择器:
$("'#News'")
Try this instead: 尝试以下方法:
$("#" + $(this).attr("data-wife")).show();
As a side note, it's simpler and preferable to use data()
to access data-
attributes: 附带说明一下,使用
data()
访问data-
属性更简单,更可取:
$("#" + $(this).data("wife")).show();
To get the value of "data-" attributes, you can use .data()
: 要获取“ data-”属性的值,可以使用
.data()
:
$('#' + $(this).data('wife')).show();
Note that you leave off the "data-" prefix. 请注意,省略了“ data-”前缀。 In your code you introduced an extra layer of quotes, which is incorrect.
在您的代码中,您引入了额外的引号层,这是不正确的。 The library just wants a string, not a string with a quoted string in it.
该库只需要一个字符串,而不是其中带有引号的字符串。
只是语法更改
$("#" + $(this).attr("data-wife")).show();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.