簡體   English   中英

函數調用未在模板文字中定義

[英]function call is not defined inside template literal

嗨我有這樣的功能,我正在嘗試建立一個降價編輯器

var Editor,
  __bind = function(fn, h) {
    return function() {
      return fn.apply(h, arguments);
    };
  };

Editor = (function() {
  function Editor(selector, options) {
    this.variable = __bind(this.varirable, this);
  }

Editor.prototype.variable = function(name) {
    this.editor.doc.replaceSelection('#' + name + '#');
    return this.editor.focus();
};

Editor.prototype._buildToolbar = function() {
    var $md = this;

$(`<div class="dropdown" style="display:inline">
  <a class="btn dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"
  style="padding:0 0 0 10px;color: #000;box-shadow: none;height:100%;line-height:26px;">v</a>
  <div class="dropdown-menu" aria-labelledby="dropdownMenuLink" style="box-shadow: 0 0px 5px 0 rgba(0,0,0,.25);border-radius: 0;margin-top: -1px;">
    ${Object.keys(this.options.vars)
      .map(function(key) {
        return (
          '<a class="dropdown-item" id="' +
          $md.options.vars[key].VariableName +
          '" href="#" onClick="variable(' +
          $md.options.vars[key].VariableName +
          ')">' +
          $md.options.vars[key].VariableName +
          '</a>'
        );
      })
      .join('')}
  </div></div>`).appendTo(this.toolbar);
};

問題是,當我點擊鏈接時,我得到了Uncaught ReferenceError: variable is not defined我甚至試圖使用$md.variable(name)調用它,但同樣的事情。

沒有必要修改Editor的原型,它不會像你調用方法那樣工作。

只是改變

Editor.prototype.variable = function(name) {
  this.editor.doc.replaceSelection('#' + name + '#');
  return this.editor.focus();
};

function variable(name) {
  this.editor.doc.replaceSelection('#' + name + '#');
  return this.editor.focus();
};

你的點擊處理程序應該工作。

問候

注意this將指向名為variable() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

暫無
暫無

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

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