[英]calling an external library function by string
在我的 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
我可以像上面顯示的那樣手動調用所有函數並且它可以工作。 但問題是這樣做我需要在我的腳本中為每個庫 function 編寫 200 個調用案例。
我決定我可以做一個輸入文本框,讓用戶調用 function,這樣他就可以編寫“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>";
如何在輸入中設置字符串的情況下通過字符串調用 function?
嘗試在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)
使用 eval()
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=\"execute(this);\">call</button>"; box += "</div>"; $('#msg').html(box); function execute(elm){ let text = elm.parentElement.getElementsByClassName('functionName')[0].value; eval("elm.parentElement.getElementsByClassName('result')[0].innerHTML=library."+text+";"); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="msg"></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.