我有这个HTML:
<span class="price">
$61.00
<span class="detailFreeShipping">With Free Shipping</span>
</span>
如何编写一个jquery选择器,它只给我价格文本“$ 61.00”?
我想让它尽可能通用,因为在某些情况下可能没有内部跨度,只有父内容。
答案 0 :(得分:11)
你可以这样做:
jQuery.fn.extend({
textOnly: function() {
// make a clone of this object so we are not changing the actual DOM
var obj = $(this).clone();
// remove all the children, i.e. any DOM objects
obj.children().remove();
// get the text value after all DOM elements are removed
return obj.text();
}
});
然后你可以这样称呼它
var price = $(".price").textOnly();
您将获得所需的价值。
答案 1 :(得分:0)
我不知道jQuery,但只是伪回复你的问题,你可以通过以下方式来做到这一点:
var elem = document.getElementById('yourid'); // or document.getElementsByTagName('span')[0];
var text = elem.innerHTML;
text = text.substr(0, (text.indexOf('<') > -1 ? text.indexOf('<') : text.length));
答案 2 :(得分:0)
尝试:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" charset="utf-8">
google.load("jquery", "1.3");
</script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
var white_out = $("span[class=price] :first-child").text();
var all = $("span[class=price]").text();
var price = all.replace(white_out, "");
alert(price);
});
</script>
</head>
<body>
<span class="price">
$61.00
<span class="detailFreeShipping">With Free Shipping</span>
</span>
</body>
</html>
行:
var white_out = $("span[class=price] :first-child").text();
var all = $("span[class=price]").text();
var price = all.replace(white_out, "");
对于单个元素,可能会完成工作。