与多个ckeditor使用checkDirty()提醒用户,如果内容已经改变之前离开页面

Working with multiple CKEditors using checkDirty() to alert user if content has changed before leaving page

本文关键字:改变 离开 如果 使用 ckeditor checkDirty 用户      更新时间:2023-09-26

我有这个代码非常适合一个CKEditor textarea字段。它在用户离开页面之前提醒他们的内容已被更改。但有些页面有多个ckeditor,我想知道我如何承认他们都使用这个JavaScript代码。

function beforeUnload( e )
{
    if ( CKEDITOR.instances.description.checkDirty() ) 
        return e.returnValue = "You will lose the changes made in the editor."; 
}
if ( window.addEventListener )
    window.addEventListener( "beforeunload", beforeUnload, false );
else
    window.attachEvent( "onbeforeunload", beforeUnload );

Description是文本区域的名称,但有些文本区域有其他名称,如products_short_description[1]products_description[1]。我需要找到一种方法,将所有CKEditor名称集成到此代码中,以便如果有人对2或3个编辑器中的一个进行更改,它会相应地提醒他们。

像这样迭代所有实例:

function beforeUnload( evt ) {
    for ( var name in CKEDITOR.instances ) {
        if ( CKEDITOR.instances[ name ].checkDirty() )
            return evt.returnValue = "You will lose the changes made in the editor."; 
    }
}