簡體   English   中英

如何調用模板文字中的函數調用

[英]How to call calling a function inside a Template literal

如何在模板文字中調用函數。

以下嘗試中的函數語法顯示在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);
});

謝謝大家。

如果我正確理解您的問題,您需要在模板文字中定義和調用該函數。

一些背景

您可以在模板文字中執行表達式,如下所示:

function fun(){
   return 5
}

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

所以這是文字內部函數的最簡單和最佳用法。 現在你要在你的例子中嘗試做的是,評估表達式

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

在模板文字內部,這為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事件,並且不會在模板文字中留下痕跡。

注意:

只需在模板文字外聲明函數並在文字內部隨意調用它是最佳選擇

這是你可以在模板文字中調用函數的方法。

function something() { 
    return "better than nothing"; 
}
console.log(`Something is ${something()}.`);
//=> Something is better than nothing.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM