在我的 js 代码中有一个循环,它根据模块的名称加载模块。每个模块都返回 HTML 代码。所有这些都归结为网站布局。例如一个非常简单的模块:
box = "<div class=\"entity_box\">";
box += "third player address: <span class=\"result\">...</span>";
box += "<button onclick=\"this.parentElement.getElementsByClassName('result')[0].innerHTML=library.returnAddress(thirdPlayer).call()\">call</button>";
box += "</div>";
该库包含数百个函数,例如:
library.returnAddress(player).call()
library.getUser(order).call()
library.getUserLevel(order).call()
library.getPrivilege(sender).call()
library.setPrivilege(player, value).call()
library.addUser(data).call()
and so on
我可以像上面显示的那样手动调用所有函数并且它可以工作。但问题是这样做我需要在我的脚本中为每个库函数编写 200 个调用案例。
我决定我可以制作一个输入文本框并让用户调用函数,这样他就可以编写“getUserLevel(25)”并单击一个按钮,然后得到一个结果。
这是我写的,它不起作用:
box = "<div class=\"entity_box\">";
box += "<input type=\"text\" class=\"inputData\" />";
box += "return val: <span class=\"result\">...</span>";
box += "<button onclick=\"library." + $(box).find('.inputData').text() + ".call()\">send</button>";
box += "</div>";
也不工作:
box = "<div class=\"entity_box\">";
box += "<input type=\"text\" class=\"inputData\" />";
box += "return val: <span class=\"result\">...</span>";
box += "<button onclick=\"let library = new Library(); library.($(box).find('.inputData').text()).call()\">send</button>";
box += "</div>";
如何在输入中设置字符串的情况下按字符串调用函数?
尝试在https://playcode.io/上执行此操作但仍然无法正常工作:
示例(不工作)代码:
function Library()
{
}
Library.prototype.returnAddress = function(playerId)
{
return 2525;
}
Library.prototype.otherTest = function(playerId)
{
return 3333;
}
let library = new Library();
box = "<div class=\"entity_box\">";
box += "Call function by name:";
box += "<br />";
box += "<input type=\"text\" class=\"functionName\" />";
box += "<br />";
box += "return data: <span class=\"result\">...</span>";
box += "<br />";
box += "<button onclick=\"let text = this.parentElement.getElementsByClassName('functionName')[0].value; this.parentElement.getElementsByClassName('result')[0].innerHTML=library.(text)\">call</button>";
box += "</div>";
$('#msg').html(box)