有一个html,看起来像:
<html>
<head></head>
<body>
<div>
<h5 id="ca1">
<span>text</span>
<strong>text</strong>
<label>text</label>
</h5>
<div>
<h5 id = "ca2">
</h5>
<div id = "ca2body">
<table>
<tbody>
<tr>
<th><span>text</span></th>
<td>sth here</td>
<th><span>text</span></th>
<td>
<label></label>
text that i don't need
<label></label>
text that i don't need
<label></label>
text that i don't need
</td>
<script>
jQuery('#g2c4').change(function(){
if(jQuery('#g2c4').prop("checked")){
jQuery('#g2c4Span').show();
jQuery('.G2d').show();
}else{
jQuery('#g2c4Span').hide();
jQuery('.G2d').hide();
jQuery.each(jQuery('.chk_g2d'), function( index, item ) {
jQuery(item).prop('checked',false).change();
});
}
});
</script>
</tr>
<tr>
<th><span>text</span></th>
<td></td>
<th><span>text</span></th>
<td>
</td>
</tr>
<tr>TheSame</tr>
<tr>TheSame</tr>
<tr>TheSame</tr>
</tbody>
</table>
</div>
<h5 id = "ca3">
</h5>
<div id = "ca3body">
<table>
<tbody>
<tr>
<th><span>text</span></th>
<td></td>
<th><span>text</span></th>
<td></td>
</tr>
<tr>
<th><span>text</span></th>
<td></td>
<th><span>text</span></th>
<td></td>
</tr>
<tr>TheSame</tr>
<tr>TheSame</tr>
<tr>TheSame</tr>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
我想获取文本:“sth here”所有 parent 标签名称。 我需要让他们连成一个词。 就像:html_body_div_table_tbody_tr_td
我该怎么办?
最后,我想制作一个Json文档。
[
{
"html_body_div_table_tbody_tr_th_span":"text",
"html_body_div_table_tbody_tr_td":""
}
]
我会尝试让它们成为一本字典, 并使用字典的key和keyvalue来做。 是不是很容易做到?
最佳答案
您可以使用parents()
const result = $('#ca2body tr').map(function() {
var $children = $(this).find('*:not(:has(*))')
var object = {}
$children.each(function() {
let key = $(this).parents().addBack().map((_, i) => i.tagName.toLowerCase()).get().join('_')
let val = $(this).text()
object[key] = val
})
return object
}).get()
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<h5 id="ca1">
<span>text</span>
<strong>text</strong>
<label>text</label>
</h5>
<div>
<h5 id="ca2">
</h5>
<div id="ca2body">
<table>
<tbody>
<tr>
<th><span>text</span></th>
<td>sth here</td>
<th><span>text</span></th>
<td></td>
</tr>
<tr>
<th><span>text</span></th>
<td></td>
<th><span>text</span></th>
<td></td>
</tr>
<tr>TheSame</tr>
<tr>TheSame</tr>
<tr>TheSame</tr>
</tbody>
</table>
</div>
<h5 id="ca3">
</h5>
<div id="ca3body">
<table>
<tbody>
<tr>
<th><span>text</span></th>
<td></td>
<th><span>text</span></th>
<td></td>
</tr>
<tr>
<th><span>text</span></th>
<td></td>
<th><span>text</span></th>
<td></td>
</tr>
<tr>TheSame</tr>
<tr>TheSame</tr>
<tr>TheSame</tr>
</tbody>
</table>
</div>
</div>
</div>
关于javascript - 如何使用JS获取html中tagName的所有父级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60842814/