function ftest (P1, P2) {
"use strict";
document.getElementById(String(P1)).display = String(P2);
}
document.getElementById(字符串(P1))
使用参数P1作为ObjectID;
显示 = 字符串(P2)
使用参数 P2 作为 ObjectStyle 属性;
这种方式可以避免在工作流程中传递值时出现困惑::
onclick="ftest(objectname,objectproperty)"
而不是
onclick="ftest('objectname','objectproperty')"
结果将是
对象为空或未知属性?
当试图让 html 代码变得干净时;
最佳答案
你不能。做到这一点的唯一方法是:
var objectname = "objectname";
然后
ftest(objectname)
可以。但是,如果您的目标是
to make things clean at the html code
然后删除内联事件监听器并执行以下操作:
// html
<button id="ftest" > ftest </ button>
// js
const on = (selector, event, handler) => document.querySelector(selector).addEventListener(event, handler);
on("#ftest", "click", () => ftest("objectname", "objectproperty"));
关于Javascript::使用变量作为对象 ID 和属性的字符串;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52464987/