如何编写动态html标记

时间:2017-10-16 20:45:17

标签: javascript html for-loop

我有这个for-in循环,它应该返回一个div元素,其中img标记具有onclick函数。出于某种原因,我在参数列表后得到此错误 - 未捕获的SyntaxError:缺失 - 我不知道我错过了哪里。任何帮助或建议将不胜感激。谢谢。

for (var key in icons) {

 var legend = document.getElementById('legend');
 //the variables below points to objects
 var type = icons[key];
 var name_place = type.name;
 var icon = type.icon;
 var div = document.createElement('div');
 div.innerHTML = '<img'  + ' src="' + icon + '"' +     
 'onclick="displayMarker( ' + name_place + ' )"' + '> ' + name_place;
  legend.appendChild(div);
}

 //When I try: 
 div.innerHTML = '<img'  + ' src="' + icon + '"' + 
 'onclick="displayMarker(name_place)"> ' + name_place;

变量name_place未传递给函数

1 个答案:

答案 0 :(得分:3)

/affiliate
var icons = {
  one: {
    name: 'name1',
    icon: 'icon1.img'
  },
  two: {
    name: 'name2',
    icon: 'icon2.img'
  }
};

function displayMarker( arg) {
  console.log("displayMarker argument %s value: %s", typeof arg, arg);
}

for (var key in icons) {

  var legend = document.getElementById('legend');
  //the variables below points to objects
  var type = icons[key];
  var name_place = type.name;
  var icon = type.icon;
  var div = document.createElement('div');
  div.innerHTML = '<img src="' + icon + '" onclick="displayMarker(\'' + name_place + '\')"> ' + name_place;
  legend.appendChild(div);
}

您需要为函数参数添加参数的引号。

由于您已经在使用单引号进行字符串表示,因此需要转义<div id="legend"></div>参数传递的字符。

建议:如果可能,请使用event delegation