は、次の点を考慮MutationObserverレコード間違ったDOM要素(編集可能なDIV)
:<div id="contentEditableDiv" contenteditable="true">
<p id="content0e">Lorem ipsum...</p>
<p id="content1e">Lorem ipsum...</p>
</div>
私はMutationObserverは、DOMはJavaScriptでこのdiv要素の変化を観察するために追加します。私はcontenteditable
div要素を持っている
を
var mutationObserver = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
manipulateAddedContent(mutation);
});
});
mutationObserver.observe(jQuery("#contentEditableDiv")[0],
{ attributes: true, childList: true, characterData: true });
この問題を解決したら、manipulateAddedContent
にします。しかし、関数は次のように宣言されています:contenteditable
で
function manipulateAddedContent(mutation){
jqMutation = jQuery(mutation);
if(jqMutation.prop("addedNodes").length > 0){
for (i = 0; i < jqMutation.prop("addedNodes").length; i++) {
console.log(mutation.addedNodes[i]);
}
}
}
は、既存のp
要素内のEnterキーを押して新しいp
DOM要素を追加することが可能であるDIVので、HTMLは次のようになります。
Inspector:
<div id="contentEditableDiv" contenteditable="true" style="...">
<p id="content0e">Lorem ipsum...</p>
<p id="content1e">Lorem ipsum...</p>
<p></p>
</div>
しかし、MutationObserverは、既に存在するp
要素をid="content1e"
と記録します。
まあ、MutationObserverがそれを正しく行うことができないことを期待して、私に代替の解決策を与えることができれば幸いです。
以下はスタックスニペットです。既存のp
要素の1つの中でカーソルをクリックしてEnterを押すと、新しいp
要素が作成されます。 MutationObserverは、既に存在するp
要素を記録するが、新たに作成された要素は記録しない。
スタックスニペット:
var mutationObserver = new MutationObserver(function(mutations) {
\t mutations.forEach(function(mutation) {
\t \t manipulateAddedContent(mutation);
\t });
});
mutationObserver.observe(jQuery("#contentEditableDiv")[0],
{ attributes: true, childList: true, characterData: true });
function manipulateAddedContent(mutation){
\t jqMutation = jQuery(mutation);
\t if(jqMutation.prop("addedNodes").length > 0){
\t \t for (i = 0; i < jqMutation.prop("addedNodes").length; i++) {
\t \t console.log(mutation.addedNodes[i]);
\t \t }
\t }
}
\t #contentEditableDiv {
\t \t border: 1px solid black;
\t \t min-height: 200px;
\t \t width: 200px;
\t }
\t #contentEditableDiv p{
\t \t border: 1px solid red;
\t \t margin-left: 5px;
\t \t margin-right: 5px;
\t }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="contentEditableDiv" contenteditable="true" >
<p id="content0">Lorem ipsum...</p>
<p id="content1">Lorem ipsum...</p>
</div>
はなぜMutationObserverは、間違った要素を記録していますか?
どうすれば修正できますか? =>新しく追加されたp
要素(IDなし)を取得する方法は?
manipulateAddedContentは、観測された最初のノード(mutation.addedNodes [0])のみを記録しています。影響を受けるすべてのノードをロギングしていないだけなのでしょうか? – raphael75
いいえ質問に変更を加えます。 'for'ループは' id = "content1e" 'を持つ' p'だけを与えます。新しい 'p'要素は、2番目の要素を追加した後に記録されます。 – goulashsoup
コードを1つの[mcve]にまとめることはできますか?たぶん[Stack Snippet](http://meta.stackoverflow.com/q/269753/215552)またはjsfiddle.netか何かを使用しますか?それはそれに沿って従うことは非常に簡単になります。 –