简体   繁体   English

在js的子菜单中添加function

[英]add a function in a submenu in js

I am having trouble adding a function to a submenu created with js.我无法将 function 添加到使用 js 创建的子菜单中。

content2 +="<li class=\"myclass\" ><a href=\"#\" onclick=\"myfuncion();\">  hi </a></li>";  


function myfuncion(){

  alert("asdsadas")

}

The issue is that I have changed the quotes and everything but I can't solve it.问题是我已经更改了引号和所有内容,但我无法解决它。

I have attached an image so you can see the error.我附上了一张图片,所以你可以看到错误。

If someone can guide me I would appreciate it.如果有人可以指导我,我将不胜感激。

Thank you very much.非常感谢。

//upgrade: //升级:

what I need through myFunction () is to pass variables, to load a web page in an iframe.我需要通过 myFunction () 传递变量,在 iframe 中加载 web 页面。

example:例子:

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;

}

The linter cannot see it is called in the string. linter 看不到它在字符串中被调用。 Why not delegate?为什么不委托?

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

Also use data-attributes.也使用数据属性。 I assume you have a { "web": "some web address" } in your object我假设您的 object 中有一个{ "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>`);

I'd recommend using the below implementation.我建议使用以下实现。 it works for anything rendered on/after page load.它适用于页面加载时/之后呈现的任何内容。

$(document).on("click",".myclass",function(){
    myfuncion();
});

To render UI elements I recommend using https://json2html.com/要呈现 UI 元素,我建议使用https://json2html.com/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM