How do I select an element whose ID is given in an attribute of another element?
<div id="_News" class="link active" data-wife="News">News</div>
I want to grab the element with the ID given in data-wife
. 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:
$("#" + $(this).data("wife")).show();
To get the value of "data-" attributes, you can use .data()
:
$('#' + $(this).data('wife')).show();
Note that you leave off the "data-" prefix. 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.
$('#_News').click(function(){
$('#'+this.dataset.wife).show();
});
只是语法更改
$("#" + $(this).attr("data-wife")).show();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.