缺少)参数列表数组参数函数后

时间:2017-02-16 04:41:14

标签: javascript

我的代码有问题,这是我的代码

value id,urlIMG,NewImg []是全局的

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
}

当我运行它时,它显示错误:

  参数列表

之后

profile.html:1未捕获的SyntaxError:missing)

当我删除像onClick="Test('+id+','+i+');"这样的srcArray时,它正在运行。 请帮帮我,谢谢!

1 个答案:

答案 0 :(得分:1)

您正在JavaScript中的HTML Test(…, …, …);内生成JavaScript(<div … onClick="…">)。这很麻烦,容易出错。幸运的是,在JavaScript中根本不需要编写HTML字符串;相反,您可以创建元素并将它们直接插入到文档中!

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

现在您可以将container放在您需要的任何地方。如果您要设置something.innerHTML = Show_Img;,现在要将元素添加为something.appendChild(container);

一些有用的(我希望)资源: