Show Class instead of ID (jQuery)

2019-08-01 10:41发布

问题:

<a href="#tab1">Tab1</a>
<div id="tab1">content</a>
...
var a = $(this).attr('href');
$(a).show();

This works but only if the container has an ID since the anchor link starts with "#", how do I make it work with a class, so that it recognized <div class="tab1">content</a>?

Many thanks

回答1:

var a = $(this).attr('href');
$(a.replace('#','.')).show();

var a = $(this).attr('href').replace('#','.');
$(a).show();


回答2:

var a = $(this).attr('href').substring(1);
$('.' + a).show();

jsFiddle.

If your a regex'r (I wouldn't use it here, however), you could use...

$(this).attr('href').replace(/^#/, '.');

jsFiddle.