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

时间:2015-03-30 08:27:28

标签: ckeditor

当我点击跨度时,我试图获取属性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);
    });

但没有任何意外......

请问怎么做?谢谢!!

1 个答案:

答案 0 :(得分:3)

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

更新 :根据以下评论,为避免CKEditor的离奇行为,最好使用attachListener代替jQuery&#39 ; s&#39; on&#39;绑定事件监听器

第一步:绑定点击事件:

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