3

div を編集可能にします。div のテキストを解析しようとしたときに、以下の正規表現を実行する必要がありました。

innerDOM = "<div style="cursor: text;">I had downloaded all the material from the Intern,<br>You will find</div><div style="cursor: text;">&nbsp;</div><div style="cursor: text;">dfvdfvdvdfvdfvdvdvdf</div><div style="cursor: text;">&nbsp;</div><div style="cursor: text;">dfvdfvdvdfvdfvdfvdfvd</div>"

innerDOM.replace(/<div style="cursor: text">/g, "<br>").replace(/<\/div>/g, "");

上記の正規表現は、firefox と chrome でうまく機能します。しかしIEではありません。どのような変更を行う必要がありますか?

理解を深めるために、このFIDDLEを参照してください...

4

3 に答える 3

4

DOM 操作は、jQueryが作成された目的の 1 つです。jQuery の学習に投資することで、DOM トラバーサルと変更の作成に向けて長い道のりを歩むことができます。

$("div[style='cursor: text']").unwrap().prepend("<br>");

unwrap要素を削除しますが、子はそのまま保持します。jQuery Attribute Equals Selectordivsは、cursor スタイル属性を持つすべてを選択するために使用されます。ここでライブで実行できます。

現在、多かれ少なかれ空白やその他の些細な違いがあるdivを選択しないため、これをより堅牢にすることができます。例:<div style="cursor:text;">上記のセレクターでは一致しません。カーソルを設定する CSS クラスを導入することで、この欠点を回避できます。この場合は次のよう<div style="cursor: text">になり<div class='textCursor'>、クラス セレクターを使用できます。$("div.textCursor")

于 2012-10-10T14:05:22.713 に答える
3

私はこのサイトでこの解決策を見つけました:

$editables = $('[contenteditable=true'];

$editables.filter("p,span").on('keypress',function(e){
 if(e.keyCode==13){ //enter && shift

  e.preventDefault(); //Prevent default browser behavior
  if (window.getSelection) {
      var selection = window.getSelection(),
          range = selection.getRangeAt(0),
          br = document.createElement("br"),
          textNode = document.createTextNode($("<div>&nbsp;</div>").text()); //Passing " " directly will not end up being shown correctly
      range.deleteContents();//required or not?
      range.insertNode(br);
      range.collapse(false);
      range.insertNode(textNode);
      range.selectNodeContents(textNode);

      selection.removeAllRanges();
      selection.addRange(range);
      return false;
  }

   }
});
于 2012-11-04T10:26:46.933 に答える
3
//FINAL ANSWER
var domString = "", temp = "";

$("#div-editable div").each(function()
            {
                temp = $(this).html();
                domString += "<br>" + ((temp == "<br>") ? "" : temp);
            });

alert(domString);

答えについては、このフィドルを参照してください。

于 2012-10-11T04:47:15.993 に答える