我有这个代码从另一个页面获取html
$.get('alertjquery.html', null, function(tsv) {
alert(tsv);
});
我想知道的是计算html页面中某个元素的数量。
我有点困惑,好像我做var data $('section').length;
它不会计算tsv
中的部分,而是计算当前html页面中的部分
这是html页面:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script>
$(document).ready(function() {
var data = $('#test').text($('section').length);
});
</script>
</head>
<body>
<section>
This should be counted
</section>
<section>
This should be counted
</section>
<section>
This should be counted
</section>
<section>
This should be counted
</section>
<section>
This should be counted
</section>
There are currently <b id='test'></b> alerts
</body>
</html>
当我将此警告为tsv时,也会打印出来 但是当我尝试$ tsv.find(“section”)。length时它返回0
答案 0 :(得分:3)
您可以使用jQuery包装HTML,然后使用您想要的任何jQuery函数:
$(tsv).find("section").length
编辑:
如果您的tsv内容未被<html>
或其他容器包装(这意味着它不是“有效”的html文档),您可以执行以下操作:
$("<div>"+tsv+"</div>").find("section").length
答案 1 :(得分:1)
这适用于所有情况,即使tsv
不是容器:
$('<div/>', {
html: tsv
}).find('section').length;