-2

I have a problem with my code, this is my code

value id,urlIMG,NewImg[] is global

var srcArray = new Array();
for(var i=0;i<num_new_data;i++)
{      
  srcArray.push(urlIMG+NewImg[i]);
  Show_Img += '<div class="col-xs-4 col-sm-5cols"  id="s_img_click_'+id+i+'" onClick="Test('+id+','+i+','+srcArray+');" > <div class="thunho"> <img id="img_'+id+i+'"  src="'+urlIMG+NewImg[i]+'" /></div></div>';
  count ++;
}

function Test(id,i,srcArray )
{
 //Something
}

When i'm run it, it show error:

profile.html:1 Uncaught SyntaxError: missing ) after argument list

When i remove srcArray like onClick="Test('+id+','+i+');" it's working. Please help me, thank you!

Lucy Vo
  • 5
  • 1
  • 4

1 Answers1

1

You’re generating JavaScript (Test(…, …, …);) inside HTML <div … onClick="…"> inside JavaScript. That’s messy and prone to error. Luckily, there’s no need to make strings of HTML at all in JavaScript; instead, you can create elements and insert them directly into the document!

// Create the <img>
var image = document.createElement('img');
image.id = 'img_' + id + i;
image.src = urlIMG + NewImg[i];

// Create <div class="thunho">
var miniature = document.createElement('div');
miniature.className = 'thunho';

// and add the image to it:
miniature.appendChild(image);

// Create the outer <div>
var container = document.createElement('div');
container.className = 'col-xs-4 col-sm-5cols';
container.id = 's_img_click' + id + i;

// and add the thumbnail to it:
container.appendChild(minature);

// Finally, add the 'click' listener as a function instead of text,
// though with some extra work; see:
// https://stackoverflow.com/questions/750486/javascript-closure-inside-loops
container.onclick = (function (i) {
    return function () {
        Test(id, i, srcArray);
    };
})(i);

Now you can put container anywhere you need it. If you were setting something.innerHTML = Show_Img;, now you would add the element as something.appendChild(container);.

Some useful (I hope) resources:

Ry-
  • 218,210
  • 55
  • 464
  • 476