将字符串值传递给动态创建的HTML元素

时间:2013-10-08 05:58:10

标签: javascript jquery html

我有阵列消息我希望将它传递给html中动态创建的元素的onclick函数。

for(var i=0; i < msg.length ; i++){

 categoryList += "<img src='../products/"+msg[i].imgurl+"' class='slide_contain' onclick='getCanvas("+msg[i].id+","+msg[i].shape+","+msg[i].height+","+msg[i].width+","+msg[i].topval+","+msg[i].leftval+","+msg[i].radius+","+msg[i].subcat+","+msg[i].imgurl+")'/>";
    categoryList += "<li> <span> "+msg[i].imgurl+"</span></li>";
}

在检查时,我看到:

<img src="../products/Lighthouse.jpg" class="slide_contain" onclick="getCanvas(2,3,100,100,100,210,100,1,Lighthouse.jpg)">

这里最后一个字符串变量没有正确传递?怎么做 ? 或者如何我可以传递msg数组来运行和获取函数中的值?

3 个答案:

答案 0 :(得分:1)

你错过了引号..

 categoryList += "<img src='../products/"+msg[i].imgurl+"' class='slide_contain' onclick='getCanvas("+msg[i].id+","+msg[i].shape+","+msg[i].height+","+msg[i].width+","+msg[i].topval+","+msg[i].leftval+","+msg[i].radius+",'"+msg[i].subcat+"')'/>";

答案 1 :(得分:1)

尝试这样的事情

categoryList += '<img src="../products/'+msg[i].imgurl+' class="slide_contain" onclick="getCanvas('+msg[i].id+','+msg[i].shape+','+msg[i].height+','+msg[i].width+','+msg[i].topval+','+msg[i].leftval+','+msg[i].radius+','+msg[i].subcat+',\''+msg[i].imgurl+'\')"/>';

答案 2 :(得分:0)

通过这种方式传递你的最后一个论点==&gt;

  \'' msg[i].subcat  '\' 
 categoryList += "<img src='../products/"+msg[i].imgurl+"' class='slide_contain' onclick='getCanvas("+msg[i].id+","+msg[i].shape+","+msg[i].height+","+msg[i].width+","+msg[i].topval+","+msg[i].leftval+","+msg[i].radius+",' \''"+msg[i].subcat+"'\' ')'/>";

输出

'Lighthouse.jpg'