复制div内容并将其放在其他位置

时间:2011-06-20 12:02:28

标签: javascript jquery

我正在自定义公告板中创建报价系统。

我需要做的是复制一个div的内容,但将其放在带有其他元素的文本区域中。

我可以使用jQuery协助我这样做吗?

我该怎么做?

5 个答案:

答案 0 :(得分:2)

操纵字符串然后复制

这可能就是你想要的:

var stringContent = $("#SourceDivID").html();
$("#TextAreaID").val("This is content:\n" + stringContent);

然后,您可以根据自己的意愿轻松操纵textarea内容。这将复制整个DIV子树(包括所有元素),而不仅仅是文本内容。但是你必须要知道DIV的内容会成为一个字符串。

操纵HTML元素,然后复制

如果你想操纵HTML元素,那么就这样做:

var div = $("#SourceDivID").clone();
// manipulate
$("#SomeSubElementID", div).append(/* add something inside at end */);
$("#SomeSubElementID", div).prepend(/* add something inside at start */);
div.before(/* add something in front */);
div.after(/* add something after it */);
...
// add to textarea
$("#TextAreaID").val(div.html());

使用.text().html()

如果您只需要使用文字内容,请使用.text()代替.html()。例如:

<div id="test">
    Some text <strong>emphasized.</strong>
</div>

每个返回的内容:

$("#test").text() => "Some text emphasized."
$("#test").html() => "Some text <strong>emphasized.</strong>"

在新元素中包装内容

如果你想将整个内容包装在一个新元素中,然后复制(这对论坛帖子来说很常见),就这样做:

var div = $("divID").clone();
// wrap it
div = div.wrap("<quote/>").parent();
// display in textarea
$("textareaID").val(div.wrap("<div/>").parent().html());

为什么我们要把它包裹两次?因为.html()只返回元素的内部HTML。因此,如果我们想要返回包装内容,我们必须再次包装它,然后显示新包装元素的内部HTML。这就是为什么需要双层包装的唯一原因。

JSFiddle示例

  • [quote][/quote]之间包装所有文字:click here
  • 包装<quote>元素中的所有元素:click here

答案 1 :(得分:2)

如果我理解你的问题......

var oldText = $('#yourTextBox').val();    
$('#yourTextboxID').val(oldText + $('#yourDiv').html())

答案 2 :(得分:1)

您可以使用类似

的内容
$("#textareaid").val($("#divid").text());

其中textareaid是您<textarea>的ID,divid<div>的ID。

答案 3 :(得分:1)

如果您的id为myDiv的div:

 alert($('#myDiv').html());

将在该div中为您提供html。

你有很多选择如何移动它:

如果你有一个id为myDestination的空div。然后

 $('#myDestination').html($('#myDiv'));

会将myDiv的内容移动到myDestination

如果您没有空的目标div,您可能还想在http://api.jquery.com/category/manipulation/dom-insertion-inside/查看jquery .Append,.Prepend等等其他选项。

如果你想从Div输出字符串(即在TextArea中显示HTML),那么它是类似的:

 $('#myTextArea').val($('#myDiv').html());

答案 4 :(得分:1)

是的,这是可能的!

D E M O

var copy = $('#content').html();

$('#textarea').html(copy.replace("\n","")); // best practice!
// $('#textarea').html(copy);  // standard way
//$('#textarea').html(copy.replace(/\r\n/g,'\n').replace(/\n/g,'<br>')); // to add <br> instead of new lines

还有更多:

例如:

JSfiddle

或:

JSfiddle

有很多方法,我在本Ex中使用过:

var copy = $('#content').text(); // you can use: .html()
$('#textarea').val(copy);


$('#textarea').val( $('#content').html() ); // or use .text()