我在向用JS创建的子菜单添加函数时遇到了麻烦。
content2 +="<li class=\"myclass\" ><a href=\"#\" onclick=\"myfuncion();\"> hi </a></li>";
function myfuncion(){
alert("asdsadas")
}
问题是,我已经改变了报价和一切,但我不能解决它。
我附上了一张图片,所以你可以看到错误。
如果有人能指引我,我会很感激的。
非常感谢。
//升级:
我需要通过myFunction()传递变量,加载iframe中的web页面。
示例:
content2 +="<li class=\"myclass\" ><a href=\"#\" onclick=\"myfuncion("www.google.com");\"> hi </a></li>";
function myfuncion(web){
var srcstring = web;
document.getElementById('iframe').src = srcstring;
}
短绒看不到它在字符串中被调用。 为什么不委派呢?
document.getElementById("ulID").addEventListener("click",function(e) {
const tgt = e.target;
if (tgt.tagName.toUpperCase() === "A" && tgt.closest("li").classList.contains("myclass")) {
myFuncion(tgt.dataset.web);
}
})
还要使用数据属性。 我假设您的对象中有一个{“web”:“some web address”}
document.getElementById("ulID").innerHTML = obj
.filter(item => item.gid === '2' && item.active === '1')
.map(item => `<li class="myclass"><a href="#" data-web="${item.web}">${item.web}</a></li>`);
我建议使用下面的实现。 它适用于页面加载时/加载后呈现的任何内容。
$(document).on("click",".myclass",function(){
myfuncion();
});
要呈现UI元素,我建议使用https://json2html.com/