Home > Enterprise >  How to use a variable in load()?
How to use a variable in load()?

Time:05-04

I found this .load( url [, data ] [, complete ] ) in the jQuery documentation. I write this

$('#myModal .modal-body').load($(this).attr('href')); 

then the complete html of the href is loaded. If I write this, it's the same

var modalUrl=$(this).attr('href');
$('#myModal.modal-body').load(modalUrl);

But when i do

$('#myModal.modal-body').load('/cms/myPage_1.html #content');

only the part between the #content is loaded. That's what I want. Unfortunately, that doesn't work if I use the variable as a url like

var modalUrl=$(this).attr('href');
$('#myModal.modal-body').load('modalUrl #content'); 

or

$('#myModal.modal-body').load(modalUrl #content);

or

$('#myModal.modal-body').load(modalUrl   '#content');

Is that even possible? I can't use a fixed url because there are different links on the site

Thanks for your help

CodePudding user response:

First, this solution is incorrect, why?

$('#myModal.modal-body').load('modalUrl #content'); 

Because you explain to the language that this variable is a string, it is very natural for it not to recognize it


Second, this solution is incorrect, why?

$('#myModal.modal-body').load(modalUrl #content);

Because you forgot the sign, add to this that you did not put id inside a double comma , like this :

$('#myModal.modal-body').load(modalUrl   "#content");

But even with this reform will not work, why? see three


Third, this solution at first glance seems correct, but it is not, why?

$('#myModal.modal-body').load(modalUrl   '#content');

Because simply the end result in the browser when render the JavaScript file will be like this:

$('#myModal.modal-body').load('/cms/myPage_1.html#content');

So what is the solution ? see four


Fourth, try this solution

You have two solutions here

  • First solution
$('#myModal.modal-body').load(modalUrl   ''   '#content');

Here we make a space between the variable and the id

  • Second solution
$('#myModal.modal-body').load(`${modalUrl} #content`);

Here, we use double commas of the type ``

The advantage of this type of double comma is that it recognizes spaces, unlike primitive double commas.

  • Related