Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Interpolating variables inside strings

I have the following jquery code which loads the #content div from another page, into the #result div on the current page:

$('a').click(function(event){
  $('#result').load('abother_page.html #content');
});

As you can see, I'm hard-coding the name of the requested file, along with the specific div I want to display, into the string that is sent with the load method.

I'm trying to make this dynamic, but my code is missing something:

// get the href of the link that was clicked
var href=$(this).attr('href');
// pass the href with the load method
$('#result').load('href #content');

Obviously this doesn't work because the href variable that i've created is not interpolated in the string. How can I do that?

I tried the following, all without success:

// Ruby-style: 
$('#result').load('#{href} #content');
// Concatenating-style
$('#result').load(href + '#content');
like image 837
stephenmurdoch Avatar asked Dec 17 '22 01:12

stephenmurdoch


1 Answers

add a space indicated by "here":

$('#result').load(href + ' #content');
                          ^---- here

an explanation of the failed attempts are as follows:

//this code used the string "href" as the url
$('#result').load('href #content');

//javascript doesn't have this syntax for wrapping variables like in PHP
$('#result').load('#{href} #content');

//this code appended "#content" like it was a hash tag
$('#result').load(href + '#content');
like image 61
Joseph Avatar answered Jan 05 '23 10:01

Joseph