简体   繁体   English

使用javascript将文本从一个div复制到另一个div

[英]copy text from one div to other div using javascript

<div id="noty">Hello</div>
<div id="noty">World</div>
<div id="noty">Nation</div>

<div id="textArea"></div>

$("#noty").click(function() {
    $("#textArea").html($("#noty").html());
});

I'm using this to copy text from one div to other by onclick function. 我正在使用它通过onclick函数将文本从一个div复制到另一个div。 But this is not working. 但这是行不通的。 It's only working on the first div. 它仅适用于第一个div。 Is there any way to accomplish this ? 有什么办法可以做到这一点?

Use something like this: 使用这样的东西:

<div class="noty">Hello</div>
<div class="noty">World</div>
<div class="noty">Nation</div>

<div id="textArea"></div>

<script>
$(".noty").click(function() {
    $("#textArea").html($(this).html());
});
</script>

https://jsbin.com/giqilicesa/edit?html,js,output https://jsbin.com/giqilicesa/edit?html,js,输出

Like this. 像这样。

 $(".noty").click(function(e) { $("#textArea").html(e.target.innerHTML); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="noty">Hello</div> <div class="noty">World</div> <div class="noty">Nation</div> <div id="textArea"></div> 

Yes. 是。 var s = ''; $('.noty').each(function () {s += $(this).html();}); $('#textarea').html(s); but change your divs to use class="noty" instead of id. 但将div更改为使用class =“ noty”而不是id。 The id should be unique. 该ID应该是唯一的。

At first, you must not use multiple id attribute . 首先, 您不能使用多个id属性 And another problem is sizzle providing jQuery as a selector engine returns result to use getElementById . 另一个问题是令人烦恼的是,将jQuery作为选择器引擎提供返回结果以使用getElementById It means even if you've declared multiple ids, you'll get just only one id element. 这意味着即使您声明了多个ID,也只会获得一个ID元素。 When consider those problems, you can get over this problem to follow this way: 考虑这些问题时,您可以按照以下方法解决此问题:

<div class="noty">Hello</div>
<div class="noty">World</div>
<div class="noty">Nation</div>

<div id="textArea"></div>
<script>
var $noty = $('.noty');
var $textarea = $('#textArea');
$noty.click(function () {
  var text = Array.prototype.map.call($noty, function (el) {
    return $(el).html();
  }).join(' ');

  $textarea.html(text);
});
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM