【问题标题】:Change a variable or call a function through text in JS?JS中通过文本改变变量或调用函数?
【发布时间】:2021-06-01 04:42:20
【问题描述】:

这可能是一个奇怪的请求,所以我会直截了当。

是否可以通过文本调用函数?例如,如果我要在我的网站上的文本框中键入“themechange”,然后我会使用该信息来调用我想要的功能?

此外,是否可以对变量做同样的事情?所以,我输入“textcolour red”,将它本身存储在一个变量中后执行.split,然后通过后端的函数使用它来“word[0] = word1”?

我已经使用 root 做过类似的事情,但我希望它比 JUST root 变量更具可扩展性。

var function1 = undefined, function2 = undefined, function3 = undefined, function4 = undefined, function5 = undefined;
var array = consolein.split(' '), function1 = array[0], function2 = array[1], function3 = array[2], function4 = array[3], function5 = array[4];
function text(){
   if (function1 == "custom"){
      if( function2 == "console"){
         if (function3 == "background"){
            inprompt = inprompt + "Background color set to: " + function4; println(); println();
            consoleback = function4; docelem.style.setProperty('--consoleback', consoleback)
         }
      }
   }
}

提前致谢。

【问题讨论】:

  • 您可以,但这并不意味着您应该这样做。应检查每个用户输入,以免他们在您的服务器上执行恶意代码
  • 我对可以添加多少个字符作为函数有一个限制,任何字符(例如分号)都会中断。哪一个(从我的脑海中)应该解决大多数问题?

标签: javascript function var


【解决方案1】:

是的,可以使用 Javascript 来做到这一点。 这实际上是一件有趣的事情,我以前也想做。

这只是一个小例子。在这种情况下,您只需制作一个命令列表,然后制定一些如何运行命令的规则。您可以通过键入 print 或更改背景颜色来打印一个单词:bgColor

var input = document.getElementById("myInput");
var commandList = {
    print: function (command) {console.log(command[1])},
    bgColor: function (command) {input.style.backgroundColor = command[1]}
}


function run(command) {
    commandList[command[0]](command);
}

input.addEventListener("keyup", function(event) {
  if (event.keyCode === 13) {
      var command = input.value.split(' ');
      run (command)
  }
});
<input type="text" id="myInput">

【讨论】:

    猜你喜欢
    • 2019-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    • 2011-08-31
    • 2022-01-24
    • 1970-01-01
    相关资源
    最近更新 更多