2

I want to create a variable with the append and HTML function. The reason is when a person clicks on a div he should be replace the element, otherwise he should add the element instead of replace it.

As example, my variable calls: var clicked = true;

My jQuery code looks like this:

// if a user clicks, replace the image
if(clicked == true){
   var type = '.html';
// else (when the page is loading), add the image
}else{
   var type = '.append';
}

// use the var type
container.find('.img') + type + (data.img);

If the image exists he should not add an new one, but he needs te replace him. If he exists he should replace the current image with the new one.

I know, I could do something like this:

if(clicked == true){
   container.find('.img').html(data.img);
}else{
   container.find('.img').append(data.img);
}

But I have a lot of elements, and I think this is a more effective way to write the code.

But is this possible?

Appel
  • 497
  • 5
  • 13

1 Answers1

2

When you get the function name as a string, You could try to use Bracket Notation to call that function.

var type = 'html';
container.find('.img')[type](data.img); //same with container.find('.img').html(data.img); 

you could refer more in here

Community
  • 1
  • 1
Mark
  • 2,041
  • 2
  • 18
  • 35