如何在模板字面量中调用一个函数

10
如何在模板字符串中调用一个函数?
下面是尝试中在HTML中显示的函数语法:
function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        var html = `
        <div class="row">
        ${reader.onload = function (e) {
            $('#image_upload_preview').attr('src', e.target.result);
        }}
        <img id="image_upload_preview" src="http://placehold.it/100x100" alt="your image" />
        </div>
        `;

        $("#test").append(html);

        reader.readAsDataURL(input.files[0]);
    }
}

$("#multi-file").change(function () {
    readURL(this);
});

提前感谢大家。

2个回答

11
如果我正确理解了你的问题,那么你想在模板字面量内定义和调用函数。
一些背景:你可以使用以下方式在模板字面量中执行表达式:
function fun(){
   return 5
}

var someLit=`some function got a value ${fun()}`

所以这是在文字中使用函数的最简单和最好的方法。现在,您在示例中要做的是评估表达式

reader.onload = function (e) {
  $('#image_upload_preview').attr('src', e.target.result);
}

在模板字面量中,this 绑定了一个 onload 事件,但是 reader.onload 的返回值会被替换到模板字面量的那个位置。

因此在输出结果中你会看到 function(){...

如果你不想在输出结果中看到该函数声明,可以立即调用该函数。

例如:

   (reader.onload = function (e) {
      $('#image_upload_preview').attr('src', e.target.result);
   })();

这将在表达式的位置返回undefined。现在,如果您想避免那个undefined,您可以从您的函数中返回一些空字符串。

  (reader.onload = function (e) {
      $('#image_upload_preview').attr('src', e.target.result);
      return '';
   })();

现在,由于您已将该函数用作回调函数,因此立即调用该函数可能没有帮助(因为您不会在那里获取e参数)。

因此,您可以在另一个函数中绑定事件,例如:

(function(){
    reader.onload = function (e) {
          $('#image_upload_preview').attr('src', e.target.result);
       }
    return '';
})();

这将声明一个函数,该函数绑定到您的onload事件,并且在模板字符串中没有痕迹。

注意:

在模板字符串外部声明函数并在需要时在模板字符串内调用它是最佳选择。


5
这是如何在模板文字中调用函数的方法。
function something() { 
    return "better than nothing"; 
}
console.log(`Something is ${something()}.`);
//=> Something is better than nothing.

2
你能够包含JavaScript方法吗?例如:var my_text = "hello world"; var my_string = \这是一个很棒的短语,去掉第一个字母:${my_text.substring(1)}``。 - user1063287
2
嗯,作为参考,你也可以这样做:var dialog_message = \<p>The cookie's value is "${Cookies.get("page_title")}"</p>\ `。这将返回类似于:The cookie's value is "home_page"`的内容。 - user1063287

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接