我从数据库Postgresql收到的数据是在浏览器中渲染的html内容,如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Employee</title>
</head>
<body>
<table>
<tr>
<td>ID</td>
<td>First Name</td>
<td>Last Name</td>
</tr>
<tr>
<td>CU0012</td>
<td>David</td>
<td>Jonh</td>
</tr>
untitle Name <!-- content I would like retrieve and manipulate -->
<tr>
<td>CU0010</td>
<td>Siv</td>
<td>Hellen</td>
></tr>
<tr>
<td>CU0009</td>
<td>Merry</td>
<td>Mug</td>
></tr>
</table>
</body>
</html>
我是否希望能够获取表中但在 tr
标记之外的文本 untitle Name
,以便之后可以对其进行操作?
事实上,在浏览器中渲染此 html 脚本之后,任何未正确包装在表格中的内容都将被迫移至表格之外,但在渲染之前,我想通过访问它来保留该内容,并且使其正确包裹到表格中。
<script>
$(document).ready(function(){
htmlTable = $('table tr').html();
htmlTable.each(function(){
// check element is in tr or not
});
})
</script>
如何在 jQuery 中存档它?谢谢。
最佳答案
当通过ajax或其他方法接收html内容时,可以使用String.prototype.replace()
删除意外的html内容或替换为预期的内容,然后再将其加载到一个html元素中。
//for example, you receive below text from the server
var serverData = '<table border="1"><tr><td>CU0012</td><td>David</td><td>Jonh</td></tr>untitle name<tr><td>CU0010</td><td>Siv</td><td>Hellen</td></tr></table>';
function loadReviseHtml(){
var reviseData = serverData.replace(/<\/tr>\s*(.+)\s*<tr>/, '</tr><tr><td style="background-color:red">$1</td></tr><tr>');
console.log(reviseData)
document.getElementById('htmlcontainer1').innerHTML = reviseData;
}
function loadOrgHtml(){
document.getElementById('htmlcontainer1').innerHTML = serverData;
}
<a onclick="loadReviseHtml()" style="background-color:green;">Click me to load revised html!</a>
<div id="htmlcontainer1" style="background-color:gray;">
No Data!
</div>
<a onclick="loadOrgHtml()" style="background-color:red;">Click me to load org html!</a>
关于javascript - 如何在jQuery中获取表中但tr标签之外的元素内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49184936/