4

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');

2 Answers 2

12

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');
Sign up to request clarification or add additional context in comments.

1 Comment

Doh, thanks! This fixes the problem, and thanks a lot for your explanations, that really makes it a lot clearer now
0

This has changed.

From 2015 in ES6 this is possible now using Template literals there is way you can read more about on this LINK

Expression interpolation

var a = 5;
var b = 10;
console.log('Fifteen is ' + (a + b) + ' and\nnot ' + (2 * a + b) + '.');
// "Fifteen is 15 and
// not 20."

In you case

// 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`);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.