简体   繁体   English

在ContentEditable更改事件的P标签中插入数据属性

[英]Insert data attribute in P tag in ContentEditable change event

I would like to insert a data attribute in the <p data-attribute="blah">...</p> tag when the user hits Enter (key 13) inside a content editable. 当用户在可编辑的内容内按下Enter键(键13)时,我想在<p data-attribute="blah">...</p>标记中插入数据属性。 I have gotten to the point of being notified when the user hits Enter but I am not sure how I can insert the attribute in the element the browser creates as default behaviour. 当用户按下Enter键时,我已经收到通知,但是我不确定如何将属性插入浏览器创建为默认行为的元素中。

Any hints? 有什么提示吗?

Thanks! 谢谢!

The best thing you can probably do is keeping track of the paragraphs. 您可能要做的最好的事情就是跟踪段落。 Once the contenteditable element has been created, you get a list of the paragraphs. 创建contenteditable元素后,您将获得段落列表。

<div id="textArea" contenteditable></div>

Javascript (with jQuery, since you used its tag): Javascript(使用jQuery,因为您使用了它的标签):

var textArea = $("#textArea"),
    pars = textArea.find("p");

textArea.on("input", function() {
    var curPars = $("p", this);
    curPars.each(function() {
        if ($.inArray(this, pars) === -1) // this is a new paragraph
            this.setAttribute("data-attribute", someIndex);
    });
    pars = curPars;
});

Deleted paragraphs will be discarded - you decide what to do with them. 删除的段落将被丢弃-您决定如何处理它们。

I used the input event because it's the most reliable event to keep track of changes on the content, including cutting and pasting from the clipboard using just the mouse. 我使用input事件是因为它是跟踪内容更改的最可靠的事件,包括仅使用鼠标从剪贴板剪切和粘贴。 Too bad it's not available on IE8 and lower, and in IE9 it doesn't fire when deleting content (!), and IIRC not even on contenteditable elements. 不幸的是,它在IE8及更低版本上不可用,并且在IE9中, 删除内容(!)时不会触发,甚至IIRC甚至在contenteditable元素上也不会触发。 Uuuugh. u。

You may want to add the propertychange event too, or you can rely on just keypress and mouseup events. 您可能也想添加propertychange事件,或者您可以仅依赖于keypressmouseup事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM