js/jquery:将contenteditable div复制到textarea,保留换行信息 [英] js/jquery: copy contenteditable div to textarea, keeping newline info

查看:263
本文介绍了js/jquery:将contenteditable div复制到textarea,保留换行信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个内容可编辑的div.它开始于一些孩子.还有一个文本区域.按下"enter"(输入)后,div的内容将复制到文本框中.

I have a contenteditable div. It starts out with some children. There is also a textarea. When "enter" is pressed, the contents of the div are copied to the textbox.

我的问题是,通过编辑div制作的任何新元素都不会以与原始子元素相同的格式进行复制;文字混在一起.他们的html看起来一样,所以这很奇怪.我需要看看新行从哪里开始.

My problem is that any new elements, made by editing the div, are not copied with the same formatting as the original children; the text is smushed together. Their html looks the same so this is odd. I need to see where a new line starts.

<div id = "e" contenteditable = "true">
    <div>line 1</div>
    <div>line 2</div>
</div>

<textarea id = "ta"></textarea>

// jquery
$(document).keypress(function(e) {
    if(e.which == 13) {  //enter
       $('#ta').val($('#e').text());
    }
});

我编辑div,添加几行并按Enter. div现在看起来像这样(Chrome检查元素):

I edit the div, adding a few lines and pressing enter. The div now looks like this (Chrome inspect element):

<div id = "e" contenteditable = "true">
    <div>line 1</div>
    <div>line 2</div>
     <div>line 3</div>
     <div>line 4</div>
</div>

这也显示为4行.但是,在文本区域中,它看起来像这样:

This also appears as 4 lines. However, in the textarea it looks like this:

line 1
line 2line3line4

我需要它看起来与页面上的内容相同,只有4行.

I need it to look the same as on the page with 4 separate lines.

在此示例中,我可以查看div并添加换行符.但是,可编辑div实际上可能包含复杂得多的html,这是复制粘贴的结果.

In this example, I could look at the div and add the line breaks myself. However, the editable div might actually contain much more complex html, the result of copy-paste.

(这与我要清除复制粘贴的文本有关.这似乎涉及将文本移至textarea,然后再次移回.但是,我需要知道是否从新行开始.)

(This is related to my wanting to clean up copy-pasted text. That seems to involve moving the text to a textarea and then back again. However, I need to know if a new line starts. )

推荐答案

更改以下Java脚本:

Change the java script for:

// jquery
$(document).keypress(function(e) {
    if(e.which == 13) {  
        var result = '';
        $('#e > div').each(function (i, e) { 
            result = result + $(e).text().trim() + '\r';
        });
       $('#ta').val(result);
    }
});

对我来说很好!希望对您有帮助!

Works fine for me! Hopes this help you!

这篇关于js/jquery:将contenteditable div复制到textarea,保留换行信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆