嗨,我有这样的功能,我正在尝试构建降价编辑器
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)
来调用它,但还是一样。
答案 0 :(得分:0)
无需修改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