有没有办法在点击时将div的文本放在另一个div中?

时间:2017-01-05 08:56:38

标签: javascript jquery function containers

是否有一种简单的方法可以将div的文本放在另一个div中?我之前用输入做过,但我使用了.val()

 <div id="someText"> Hello </div>
 <div id="putHere"> </div>

我很乐意帮忙,谢谢!

5 个答案:

答案 0 :(得分:4)

您正在寻找.text()

&#13;
&#13;
$(document).ready(function() {
$('#click,#div2').on('click',function() {
   $('#div2').text($('#div1').text());
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">Foo</div>
<div id="div2">Bar</div>

<button id="click">Click</button>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

如果您有兴趣,这是一个纯粹的Javascript解决方案:

&#13;
&#13;
document.getElementById('someText').onclick = function(){
  document.getElementById('putHere').textContent = document.getElementById('someText').textContent;
};
&#13;
<div style='background:red' id="someText"> Hello </div>
<div style='background:blue' id="putHere"> </div>
&#13;
&#13;
&#13;

更新:删除按钮,因为OP不需要。现在点击红色div,将填充蓝色div

答案 2 :(得分:1)

使用jQuery!

点击div上的活动

&#13;
&#13;
$(document).ready(function (){
  $("#someText").on("click", function (){
      $("#putHere").text($(this).text());
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="someText"> Click Me! </div>
<div id="putHere"> </div>
&#13;
&#13;
&#13;

点击Button上的活动

&#13;
&#13;
$(document).ready(function (){
  $("#btn").on("click", function (){
      $("#putHere").text($("#someText").text());
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="someText"> Hello World! </div>
<div id="putHere"> </div>
<button id="btn">Click ME !</button>
&#13;
&#13;
&#13;

纯JS

点击button上的活动

&#13;
&#13;
document.getElementById("btn").onclick = function() {
  document.getElementById("putHere").innerHTML =  document.getElementById("someText").innerHTML;
};
&#13;
<div id="someText">Hello World!</div>
<div id="putHere"></div>
<button id="btn">Click ME !</button>
&#13;
&#13;
&#13;

点击div上的活动

&#13;
&#13;
document.getElementById("someText").onclick = function() {
  document.getElementById("putHere").innerHTML =  document.getElementById("someText").innerHTML;
};
&#13;
<div id="someText">Click Me!</div>
<div id="putHere"></div>
&#13;
&#13;
&#13;

答案 3 :(得分:1)

这应该有效

$('#putHere').text($('#someText').text());

答案 4 :(得分:1)

&#13;
&#13;
$("button").click(function()  {
  $("#putHere").html($("#someText").text());
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="someText"> Hello </div>
<div id="putHere"> </div>
<button>Click</button>
&#13;
&#13;
&#13;