如果我想使用jQuery获取文本节点的值,我该怎么做?
例如,如果使用以下HTML,我将如何仅使用值“XYZ-123”而无需使用正则表达式解析“SID:”:
<div id="sid"><strong>SID: </strong> XYZ-123</div>
答案 0 :(得分:2)
尝试将filter()
与nodeType
Node.TEXT_NODE
:
$('#sid').contents().filter(function() {
return this.nodeType === Node.TEXT_NODE;
}).text();
上面的代码根据nodeType
查找内容和过滤器。我们只对文本节点感兴趣。
<强>段强>
$(function () {
a = $('#sid').contents().filter(function() {
return this.nodeType === Node.TEXT_NODE;
}).text();
alert(a);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="sid"><strong>SID: </strong> XYZ-123</div>
&#13;
了解更多:
答案 1 :(得分:0)
您可以使用获取div元素的内容以及filter函数来获取文本节点元素:
$('#sid').contents().filter(function() {
return this.nodeType === 3; //get text nodes
}).text();
<强> Working Demo 强>