html 添加 link 以使用 arg obj 调用 selfFunction

html add link for call selfFunction with arg obj

有可能在 html 中传递一个带有自函数的 link 并从范围

传递 arg OBJ

例子

 function notifier_ADD(ZZZ) {
   let message = /*html*/`<a href="#" onclick="callback_WithArg_Scoped(ZZZ);">Run JavaScript Code</a>`;
};

如何在活动中通过ZZZ

onclick="callback_WithArg_Scoped(ZZZ)"

嗯,模板文字:

假设 ZZZ 是一个字符串。

function notifier_ADD(ZZZ) {
  document.body.innerHTML += 
  `<a href="#" onclick="callback_WithArg_Scoped('${ZZZ}');">Run JavaScript Code</a>`;
}

function callback_WithArg_Scoped(str) {
  console.log(str);
}

notifier_ADD('Ele from SO');

如果 ZZZ 是一个对象,您可以创建元素 a:

function notifier_ADD(ZZZ) {
  var a = document.createElement('a');
  a.href = "#";
  
  a.addEventListener('click', function() {
    callback_WithArg_Scoped(ZZZ);
  });
  
  a.appendChild(document.createTextNode('Run JavaScript Code'));
  
  document.body.appendChild(a);
}

function callback_WithArg_Scoped(obj) {
  console.log(obj);
}

notifier_ADD({message: 'Ele from SO'});

或者,您可以使用 JSON.stringify()JSON.parse() (这适用于现代浏览器):

function notifier_ADD(ZZZ) {
  document.body.innerHTML += 
  `<a href="#" onclick="callback_WithArg_Scoped('${encodeURIComponent(JSON.stringify(ZZZ))}');">Run JavaScript Code</a>`;
}

function callback_WithArg_Scoped(obj) {
  console.log(JSON.parse(decodeURIComponent(obj)));
}

notifier_ADD({message: "Ele from SO"});