使用jQuery从HTML字符串中过滤HTML元素

时间:2018-07-10 21:50:05

标签: jquery html

我正在尝试使用jQuery从HTML字符串中过滤出不同的HTML标签。这是我的代码现在的样子:

$.get("check-in.php", {value: inputValue}).done(function(data) {
  var checkinSuccessStr = $("<p/>", { html: data }).find("#success").html();
  var checkinFailStr = $("<p/>", { html: data }).find("#fail").html();
  var tr = $("<tr/>", { html: data }).find("tr").html();

  console.log(checkinSuccessStr); // >> Success String
  console.log(checkinSuccessStr); // >> Failure String
  console.log(tr); // >> undefined
}

其中check-in.php将呈现以下HTML:

"<p id='success'>Success String</p>
<p id='fail'>Failure String</p>
<tr><td>Table cell</td><td>Another cell</td></tr>"

在jQuery中获取checkinSuccessStrcheckinFailStr可以正常工作,但不能在表行中工作。我尝试在结果$.parseHTML变量上使用tr,但没有成功。如何从HTML文本中获取<tr>元素(或作为数组或<tr> s的元素),作为字符串本身还是DOM元素?

2 个答案:

答案 0 :(得分:0)

答案:

HTML并非完全有效,因为<tr> must have <table>(或<thead><tbody><tfoot>)作为父级,因此解析的表示形式不包含任何<tr>标签。

<tr>包裹在<table>中应该可以解决此问题(理想情况是在php中,但最坏的情况是在解析字符串之前)。

演示:

您可以通过使用/不使用<table>包装器来打印jQuery的代码片段解析表示来看到这一点:

console.log("Broken:", $(`
<p id='success'>Success String</p>
<p id='fail'>   Failure String</p>
<tr>
    <td>Table cell</td>
    <td>Another cell</td>
</tr>
`).find("tr").html());

console.log("Fixed:", $(`
<p id='success'>Success String</p>
<p id='fail'>   Failure String</p>
<table>
    <tr>
        <td>Table cell</td>
        <td>Another cell</td>
    </tr>
</table>
`).find("tr").html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
(Try running the snippet!)

答案 1 :(得分:0)

要解析损坏的表字符串,请使用选择器'>',如下所示:

var part_table_str='<tr><td>Table cell</td><td>Another cell</td></tr>';
var cell_counter=0; //only for demonstration
$(part_table_str).find('>').each(function(){
	  console.log('cell '+cell_counter+' => '+$(this).html());
	  cell_counter++;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>