CKEditor - 使用 Onclick 获取元素的属性

CKEditor - get attribute of element with Onclick

我试图在单击跨度时获取属性 data-time-start 的值。

我的 FIDDLE : http://jsfiddle.net/zagloo/7hvrxw2c/20/

HTML :

    <textarea id="editor1"> <span class="sub" id="sub1" data-time-start="0">Hello </span>
         <span class="sub" id="sub2" data-time-start="2">My </span>
         <span class="sub" id="sub3" data-time-start="6">Name </span>
         <span class="sub" id="sub4" data-time-start="8">Is </span>
         <span class="sub" id="sub5" data-time-start="12">Zoob</span>
    </textarea>

我的 JS:

var textarea;

$(document).ready(function () {
    textarea = $('#ckeditor_block').find('textarea').attr('id');
    ckeditor_init();
});

function ckeditor_init() {
    CKEDITOR.replace(textarea, {
        language: 'fr',
        allowedContent: true
    });
}

我试过这个:

CKEDITOR.on('click', function (e) {
        var element = $(e.target);
        console.log(element);
        var cursor = element.data("timeStart");
        console.log(cursor);
    });

但是什么也没发生...

请问该怎么做?谢谢!!

在这种情况下你不能(或者更好的是你不应该)使用默认的 jQuery event/element 处理,因为 CKEditor 有它自己的事件/元素系统。

Update:根据下面的评论,为了避免 CKEditor 的古怪行为,最好使用 attachListener jQuery 的 'on' 绑定事件监听器

第一步:绑定点击事件:

var editorInstance = CKEDITOR.instances['editor1'];
editorInstance.on('contentDom', function() {
    editorInstance.editable().attachListener( 
        this.document, 
        'click', 
        function( event ) {
            // execute the code here
        }
    );
});

第二步:查找并访问数据属性:

var editorInstance = CKEDITOR.instances['editor1'];
editorInstance.on('contentDom', function() {
    editorInstance.editable().attachListener( 
        this.document, 
        'click', 
        function( event ) {
            /* event is an object containing a property data
            of type CKEDITOR.dom.event, this object has a 
            method to receive the DOM target, which finally has 
            a data method like the jQuery data method */

            event.data.getTarget().data('time-start');
        }
    );
});

有关详细信息,请查看 CKEditor docs

Updated fiddle is here