我正在尝试使用 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>
$("#foo2").text($("h1").text());
<script type="text/javascript">
$(function() {
var str = $("h1").text();
$("#foo2").html(str);
$("#foo2").replaceWith( str );
});
</script>
你的代码可以工作,只需在它周围放置$(function() {//你的代码在这里});
这应该有效:
$('#foo2').text($('h1').text());
正如Jamiec所建议的那样,不要忘记将其包装在$(document.ready();
中:
$(document).ready(function() {
$('#foo2').text($('h1').text());
});
否则,它将在 DOM 加载之前执行,这意味着它不会找到任何内容。
以下页面可能对您有用:
获取标记值或元素内容