spike spike - 1 year ago 256
Javascript Question

jQuery '#' + data("target") pattern

I've seen this a bunch:

<a href="#" id="trigger" data-target="content">Click me</a>
<div id="content">And something will happen here</div>

With JS like this:

$("#" + $(this).data("target")).hide();

It looks a little weird to me to be doing this string concatenation to create selectors which are then used to get the target element. Is there a better pattern in Javascript (with jQuery available) for setting up handlers on one element which need to know about another target element?

Answer Source

Why you do string concatenation just store the id with #

<a href="#" id="trigger" data-target="#content">Click me</a>


Similarly you can store any selectors as is in data-target say for ex:- .tab1 etc so that you do not have to perform string concatenation again inside the click or any event.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download