CKEDITOR - 单击元素时从Parent获取属性

时间:2015-05-05 08:08:52

标签: javascript jquery ckeditor

当我点击CKEDITOR正文中的元素时,我试图获取属性"data-time-start"的值。

我的FIDDLE:http://jsfiddle.net/7hvrxw2c/25/

HTML:

<div id="ckeditor_block">
    <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"><strong>Name</strong></span>
       <span class="sub" id="sub4" data-time-start="8"><strong><span style="color:#800080;">was</span></strong></span> 
       <span class="sub" id="sub5" data-time-start="12">Zoob</span>
    </textarea>
</div>

我的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
    });

    var editorInstance = CKEDITOR.instances['editor1'];
    editorInstance.on('contentDom', function () {
        editorInstance.editable().attachListener(this.document, 'click', function (event) {
            console.log(event.data.getTarget().data('time-start'));
        });
    });
}

适用于单词MyZoob但如果点击带有style colorstrong或其他任何内容的文字,则会返回null

我试图添加这样的条件,但没办法...

if (element.$.className === "st") {
   cursor = event.data.getTarget().data("time-start");
} else {
   cursor = event.data.getTarget().$.parentElement.offsetParent.firstElementChild;
}

请问怎么做?谢谢!!

1 个答案:

答案 0 :(得分:2)

在这里,我从jquery closest()方法

中找到了值
editorInstance.on('contentDom', function () {
    editorInstance.editable().attachListener(this.document, 'click', function (event) {
        var el = event.data.$.target.closest("span.sub");
        console.log($(el).data('time-start'));
    });
});

查看此jsFiddle