spike spike - 5 days ago 6
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:

$("#trigger").click(function(){
$("#" + $(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?

PSL PSL
Answer

Why you do string concatenation just store the id with #

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

$("#trigger").click(function(){
  $($(this).data("target")).hide();
})

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.

Comments