我有一个 js 函数,它接收一个项目数组。该函数本身使用 jquery html 函数调用动态创建 html 内容。问题是我不记得如何将数组正确嵌入到附加的 html 中。例如,
var ErrorsNotifier = {
init: function(items) {
var template = '<div id="message">';
template += '<div id="id">some message.<br /><br />';
template += '<div class="errorsList">error desc</div></div>';
template += '<a href="#" class="goback" onclick="ErrorsNotifier.Back("+items+");"></a>';
template += '<a href="#" class="proceed" onclick="ErrorsNotifier.Next();"></a>';
template += '<input type="image" src="someimage" alt="" class="" onclick="window.open("someurl");"/></div>';
$("#content").html(template);
}
}
将 html 渲染到正文后,单击 anchor 标记会返回以下错误 - Uncaught SyntaxError: Unexpectedidentifier
检查浏览器中的 anchor 标记将显示以下内容
a href="#" class="goback" onclick="ErrorsNotifier.Back([object Object]);"
最佳答案
尝试
var ErrorsNotifier = {
init: function(items) {
...
var $template = $(template);
$template.find('a.goback').on('click', function(){ErrorsNotifier.Back(items);});
$("#content").empty().append($template);
}
}
请注意,我使用了 .on()
来附加事件处理程序。
关于javascript - 在动态创建的 html 中嵌入 javascript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13573439/