在打印之前检查 Ajax 成功响应

Check Ajax success response before printing it out

我从 Ajax 调用中得到一些带有 div 块的 html 代码。我想在这个 html 上构建一个 if/else 检查,更具体地说是在返回的 div 的 id 属性上。如果它小于或大于 10,我会打印不同的结果。

要从 ajax 调用返回的 html:

    <div id="10" class="names">Text</div>
    <div id="2" class="names">Text</div>
    <div id="10" class="names">Text</div>
    <div id="11" class="names">Text</div>

Ajax 通话

$.ajax({
  type: "POST",
  url: "https://example.com/api",
  data: data,
  cache: false,
  success: function(html) {
    //check html response for the id attribute, print html after the check 
  },
  error: {}
});

知道怎么做吗?

是这样的吗?

注意你有两个 id="10"

const html = `<div id="10" class="names">Text</div>
<div id="2" class="names">Text</div>
<div id="10" class="names">Text</div>
<div id="11" class="names">Text</div>`

function success(html) {
    //check html response for the id attribute, print html after the check 
   const res = $("#content").html(html)
   .find("div")
   .map(function() {
     return $(this).attr("id")
   }).get();
   console.log(res,res.includes('10') ? 'has id 10' : 'does not have id 10')
}

success(html)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="content"></div>