Pro*_*Rev 5 html javascript jquery template-literals
我该如何去调用Template文字内部的函数。
以下尝试中的函数语法在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.
| 归档时间: | 
 | 
| 查看次数: | 4029 次 | 
| 最近记录: |