contentEditable field to maintain newlines upon database entry

前端 未结 3 1569
深忆病人
深忆病人 2020-12-29 08:41

I have a div with the attribute contentEditable set.

This allows me to have a free-form editable textarea, without the need for any form input fields: http://jsfiddl

3条回答
  •  没有蜡笔的小新
    2020-12-29 09:09

    jQuery uses textContent on a Node to return the text value of an element, which will compress white space. If you want the line breaks to be maintained, you need to use innerText which means accessing the element directly rather than through jQuery.

    From your jsfiddle:

    console.log($(Comments)[0].innerText);
    

    http://jsfiddle.net/M8wx9/10/

    ==== update:
    As a caveat to this (as Tim Down has pointed out), using innerText will only work in webkit and microsoft browsers. If your application also supports Firefox, you will need to use regular expressions on the innerHTML in order to maintain line breaks. As an example:

    $(Comments).html().trim()
    .replace(//ig, '\n') // replace single line-breaks
    .replace(/<[p|div]\s/ig, '\n$0') // add a line break before all div and p tags
    .replace(/(<([^>]+)>)/ig, "");   // remove any remaining tags
    

    http://jsfiddle.net/M8wx9/12/

    As mentioned in the comment, the previous is not working in Chrome. Here is a working solution:

    $(Comments).html().trim()
    .replace(//ig, '\n') 
    .replace(/(<(p|div))/ig, '\n$1') 
    .replace(/(<([^>]+)>)/ig, "");
    

    http://jsfiddle.net/M8wx9/81/

提交回复
热议问题