从h1中查找文本并使用它来替换foo2文本

Dan*_*382 6 jquery

我正在尝试使用jQuery来查找H1中的文本,然后使用它来替换foo2中已有的文本.示例如下:

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Take text from element</title>
<script type="text/javascript">
var str = $("h1").text();
    $("#foo2").html(str);
    $("#foo2").replaceWith( str );
</script>
</head>

<body>

<div id="foo"><div id="foo2">replace with h1</div></div>

<h1>Text I want to take</h1>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

Mah*_*bub 21

$("#foo2").text($("h1").text());
Run Code Online (Sandbox Code Playgroud)


Sar*_*est 5

<script type="text/javascript">
 $(function() {
  var str = $("h1").text();
  $("#foo2").html(str);
  $("#foo2").replaceWith( str );
 });
</script>
Run Code Online (Sandbox Code Playgroud)

您的代码有效,只需将 $(function() { // 您的代码放在这里 }); 周围。