我正在采用所见即所得的编辑器SummerNote,但在保存脚本时却遇到了问题,因为脚本利用了我想变成onclick事件的“ onblur”回调函数。
这是保存页面的功能,
$(function() {
var editElements = {};
$('.editable').summernote({
airMode: false,
toolbar: [
// [groupName, [list of button]]
['style', ['style']],
['font', ['bold', 'italic', 'underline', 'clear']],
['font', ['fontsize', 'color']],
['para', ['paragraph']],
['insert', ['link','image', 'doc', 'video']], // image and doc are customized buttons
['table', ['table']],
['misc', ['codeview']],
],
placeholder: 'Click here to enter content.',
callbacks: {
onChange: function(contents, $editable) {
editElements[$(this).attr('id')] = contents;
},
/* onBlur: function() {
if (editElements[$(this).attr('id')]!=undefined) {
var id = $(this).attr('id');
var content = editElements[$(this).attr('id')];
var target = ($(this).attr('data-target')!=undefined) ? $(this).attr('data-target'):'pages';
editElements[$(this).attr('id')] = undefined;
$.post("",{
fieldname: id,
content: content,
target: target,
token: token,
})
.done(function() {
$("#save").show();
$('#save').delay(100).fadeOut();
});
}
} */
},
});
});
并且这是尝试将onblur回调引入具有空内容返回的click事件函数中。
$(document).on('click','#addsave', function(e){
editElements[$(this).attr('id')] = contents;
if (editElements[$(this).attr('id')]!=undefined) {
var id = $(this).attr('id');
var content = editElements[$(this).attr('id')];
var target = ($(this).attr('data-target')!=undefined) ? $(this).attr('data-target'):'pages';
editElements[$(this).attr('id')] = undefined;
$.post("",{
fieldname: id,
content: content,
target: target,
token: token,
});
}
});
但据我所知,在错误选择$(this)选择器期间,此操作不起作用,因为它指向单击按钮实例上的可编辑内容区域为空。因此,问题是函数引用或选择器作为“ .editable”加载为“ div class editable”-如何将上面的“ onblur”回调转换为按钮单击函数?任何建议,非常感谢,问候
您可以通过在函数上使用'this
'函数将值绑定到函数内的Function.prototype.bind()关键字。
在此代码示例中,我假设页面上只有一个.editable
元素:
// create your event handler
var save = function() {
editElements[$(this).attr('id')] = contents;
if (editElements[$(this).attr('id')]!=undefined) {
var id = $(this).attr('id');
var content = editElements[$(this).attr('id')];
var target = ($(this).attr('data-target')!=undefined) ? $(this).attr('data-target'):'pages';
editElements[$(this).attr('id')] = undefined;
$.post("",{
fieldname: id,
content: content,
target: target,
token: token,
});
}
}
// get a reference to the .editable elemement
var that = document.getElementsByClassName('.editable')[0];
// bind it to 'this' in our click event handler
$(document).on('click','#addsave', save.bind(that));
感谢建议的解决方案-也考虑了绑定,尽管实际需要替换3个“ textarea”(在测试过程中删除),但您提供的脚本仍在为单个“ .editable”实例返回“ undefined”值通过wysiwyg(SummerNote)脚本快速运行到可编辑的div,这是在textarea中注入模糊效果并按说明进行保存。感谢您提出的选项,但必须进一步检查,并会提供其他信息。问候