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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13932762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:06:13  来源:igfitidea点击:

Find text from h1 and use it to replace foo2 text

jquery

提问by Dan382

I'm trying to use jQuery to find the text within H1 then use this to replace the text already in foo2. Example below:

我正在尝试使用 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>

回答by Mahbub

$("#foo2").text($("h1").text());

回答by qwerty

This should work:

这应该有效:

$('#foo2').text($('h1').text());

And as Jamiec suggested, don't forget to wrap it in $(document.ready();:

正如 Jamiec 建议的那样,不要忘记将其包装在$(document.ready();

$(document).ready(function() {
    $('#foo2').text($('h1').text());
});

Otherwise it will execute before the DOM has loaded, meaning it will find no content.

否则它将在 DOM 加载之前执行,这意味着它将找不到任何内容。

回答by Sarah West

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

Your code works, just put $(function() { // your code here }); around it.

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

回答by Gaz Winter

The following page may be useful to you:

以下页面可能对您有用:

Getting the tag value or element content

获取标签值或元素内容