如何获取 span 元素的内容 'This is my name'?
<div id='item1'>
<span>This is my name</span>
</div>
如何获取 span 元素的内容 'This is my name'?
<div id='item1'>
<span>This is my name</span>
</div>
我认为这应该是一个简单的例子:
$('#item1 span').text();
或者$('#item1 span').html();
$("#item1 span").text();
<span id="span_id">Client</span>
$("#span_id").text();
有人帮我检查错误并发现他使用了val()而不是text(),在span中无法使用val()函数。
$("#span_id").val();
将返回null。
$('#item1 span').text()
由于您没有提供'item'值的属性,我假设使用了一个类:
<div class='item1'>
<span>This is my name</span>
</div>
alert($(".item span").text());
确保在DOM加载完成后再使用代码,在jQuery中,您可以使用ready()
函数来实现:
<html>
<head>
<title>jQuery test</title>
<!-- script that inserts jquery goes here -->
<script type='text/javascript'>
$(document).ready(function() { alert($(".item span").text()); });
</script>
</head>
<body>
<div class='item1'>
<span>This is my name</span>
</div>
</body>
$('#item1').text(); 或 $('#item1').html();
对于 id="item1"
的元素可以正常工作。
document.getElementById('item1').innerText
吗? $('span id').text(); worked with me
$('#id span').text()
就是答案!
关于 .text() 和 .html() 之间的区别,以下是非常重要的附加信息:
如果您的选择器选择了多个项目,例如您有两个类似于以下内容的 span 元素
<span class="foo">bar1</span>
<span class="foo">bar2</span>
,
那么
$('.foo').text();
将连接这两个文本并将其返回;而
$('.foo').html();
只会返回其中一个。
.text()
函数会对其找到的任何字符进行 HTML 编码,而.html()
函数则不会对字符进行编码。 - VoidKing$('.class').each(function() { $(this).html() });
; 因为$('.class').html()
将返回第一个元素的.html()值。 - tomsihaptext()
,它将遍历所有子节点并连接结果。 - Scott Anderson