JQuery template '#' + data ("target")
I saw this 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 seems strange to me that I am doing this string concatenation to create selectors, which are then used to get the target element. Is there a better template in Javascript (with jQuery available) for setting up handlers on one element that should know about another target element?
Why are you doing string concatenation, just save the id with #
<a href="#" id="trigger" data-target="#content">Click me</a> $("#trigger").click(function(){ $($(this).data("target")).hide(); }) In the same way, you can store any selectors, as indicated in the data-target , for example, for ex: - .tab1 , etc., so that you do not have to perform string concatenation again inside the click or any event.
Why not do something like this, a much better approach in my opinion:
// Set the target $("#trigger").data('target', $('#content')); // Get the target $("#trigger").click(function(){ $(this).data("target").hide(); }) If you install it from the backend, I would include a hash with the attribute value, as others suggested.
<a href="#" id="trigger" data-target="#content">Click me</a> $("#trigger").click(function(){ var target = $(this).data("target"); $(target).hide(); }) You can just use
$('#content').modal('toggle'); Anyone where you are in the code to initiate a modal show and hide, you can directly use the "show" / "hide" functions.
I assume you are using Bootstrap and one of the latest versions of jQuery.
Enjoy it!
You always have the opportunity to create a selector; it looks a little better than concatenating a string inside a selector.
$("#trigger").click(function(){ var selector = "#" + $(this).data("target"); $(selector).hide(); }); A little nicer, not sure if this is what you are looking for.
I would completely skip the data, thereby allowing graceful degradation.
<a href="#content" id="trigger" data-target="">Click me</a> <div id="content">And something will happen here</div> from
$("#trigger").click(function(e){ e.preventDefault(); $( $(this).attr("href") ).show(); // note, i'm purposly not using this.href due to a bug in IE that would return the entire href rather than just the hash }) $ (this) .attr ('data-target', '#myTarget');
it worked for me
All Articles