首页 > 解决方案 > 如何将代码作为参数值传递?

问题描述

我正在尝试构建一个 JS 库,并且我想将代码作为函数的参数传递。我该怎么做?

我尝试过许多其他方式传递参数,但它不起作用。

这就是我调用函数时想要的方式。

var input = new oTinput({
  element: '#otinput',
  onFileChange: function(file){
    console.log('File name is: '+file.name);
    $("#rlly").attr("src", URL.createObjectURL(file));
    document.getElementById("rllly").load();
    console.log("Audio is loaded!");
    /*var audiofile = document.getElementsByTagName('audio')[0];
    audiofile.src = file;*/
    //function handleFiles(event) {
      //var files = event.target.files;
      /*$("#rlly").attr("src", URL.createObjectURL(file[0]));
      document.getElementById("rllly").load();
      console.log("Audio is loaded!");*/
    //}

    //document.getElementById("rll").addEventListener("change", handleFiles, false);
  },

请注意,这正是我想要的。这个 JS 库是 oTinput。

标签: javascript

解决方案


您不能直接传递代码,因为代码块 ( {}) 会立即运行,并且不会“返回”任何内容......(并且在语法上也是无效的)。

为了保留一些代码供以后使用,这就是函数的用途。

所以,只需创建一个新函数并传递它!

()=>{/* some code */}将创建一个箭头函数(在此处阅读更多信息):

var input = new oTinput(() => {
  element: '#otinput',
  onFileChange: function(file){
    console.log('File name is: '+file.name);
    $("#rlly").attr("src", URL.createObjectURL(file));
    document.getElementById("rllly").load();
    console.log("Audio is loaded!");
    /*var audiofile = document.getElementsByTagName('audio')[0];
    audiofile.src = file;*/
    //function handleFiles(event) {
      //var files = event.target.files;
      /*$("#rlly").attr("src", URL.createObjectURL(file[0]));
      document.getElementById("rllly").load();
      console.log("Audio is loaded!");*/
    //}

    //document.getElementById("rll").addEventListener("change", handleFiles, false);
  })

推荐阅读