我正在尝试通过 html 进行解析并获取所有 <h3>...</h3>
在 <table>...</table>
旁边, 但只得到第一个 <h3></h3><table></table>
来自 $('h3 + table', thecontents)
.另外,如果我们想要 h3
怎么办?基于它的内容(即 12 月 14 日,星期五,12 月 15 日,星期六,...)?
$( document ).ready(function() {
$.getJSON('http://www.whateverorigin.org/get?url=' + encodeURIComponent('...') + '&callback=?', function(data){
var thecontents = data.contents;
var required = $('h3 + table', thecontents).html();
$("#hello").html("<pre>" + required + "</pre>");
});
});
thecontents
的内容或 data.contents
是
<html>
...
<h3><strong>Friday, Dec. 14</strong></h3>
<table>...</table>
...
<h3>...</h3>
<table>...</table>
</html>
我当前的网站返回 required
或 $('h3 + table', thecontents).html()
<html>
<body id="hello">
<pre>
<p></p>
...
<p></p>
</pre>
</body>
</html>
最佳答案
您要转换的代码或 parse string to html
错了,应该是这样的
var thecontents = $('<div></div>').html(data.contents)
解析后得到h3
和 table
但是 table
的前一个元素应该是 h3
你可以试试这个
$(document).ready(function() {
$.getJSON('http://www.whateverorigin.org/get?url=' + encodeURIComponent('...') + '&callback=?', function(data) {
var thecontents = document.createElement('html')
thecontents.innerHTML = data.contents;
var required = $(thecontents).find('h3 + table');
var theResults = '';
$.each(required, function(i, obj) {
// .prev() used to get previous sibling or h3
theResults += $(obj).prev()[0].outerHTML + '\n';
// the table
theResults += obj.outerHTML + '\n';
})
$("#hello").html("<pre>" + theResults + "</pre>");
});
});
它使用 .outerHTML
得到类似 <h3>Title</h3>
的字符串同时 .html()
将返回 innerHTML
或 Title
仅。
关于javascript - 使用 Jquery 选择所有旁边,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53927329/