解析AJAX HTML响应:我可以找到元素,但不能访问它们的innerHTML或值

Parsing AJAX HTML Response: I can find the elements but not access their innerHTML or values?

本文关键字:访问 但不能 或值 innerHTML 元素 响应 HTML AJAX 我可以 解析      更新时间:2023-09-26

我正在向.aspx脚本发出AJAX请求&它返回HTML。我在JQuery中解析返回的HTML时遇到了问题,比如我无法访问某些HTML元素值或innerHTML。

你能告诉我我做错了什么吗;我该怎么修

我将脚本称为test.aspx;它只返回这个(绝对没有其他):

<input type="hidden" id="clientIndex" value="4"></input>
<div id="clientContent"> ...some html </div>

当我解析这个HTML时,我无法访问inputs值或div innerHTML,但我可以访问input&div对象很好(它们存在)。

我使用的代码是:

  $.ajax(
  {
      type: "POST",
      url: "test.aspx",
      data: "i=" + $(".clientIndexClass:first").val(),
      dataType: "html"
  }).done(function (msg) {
      // NOTE: msg has the correct html so its sending back the right formatted HTML
      var index = $(msg).find("#clientIndex").val();
      var content = $(msg).find("#clientContent").html();
      // ERROR HERE: content is null & index is undefined when it shd be text for both
      console.log("AJAX Response: " + index + ", " + content + ", " + msg);
      $(treadmill).html($(treadmill).html() + content);
      if (index == "-1") {
          console.log("killing intervals coz = -1");
          clearInterval(ele.ajaxInterval);
          clearInterval(ele.slideshowInterval);
      }
  });

在上面的代码中,我可以找到ID为"clientIndex"answers"clientContent'使用$(msg).find("#clientIndex")但是我无法访问clientIndex的值?即$(msg).fund("#clientIndex").val();返回null????

在上面的代码中,我可以找到ID为"clientIndex"answers"clientContent'使用$(msg).find("#clientIndex");

我敢肯定你找不到这样的东西。.find()仍然会返回一个jQuery对象,但我确信您会发现它的长度是0,因为没有找到任何元素。

问题是.find()在所选元素的子体中查找匹配项。在您的案例中,正好有两个没有子体的"顶级"元素。解决方案是使用.filter()方法:

var $msg = $(msg),
    index = $msg.filter("#clientIndex").val(),
    content = $msg.filter("#clientContent").html();

注意:我将$(msg)的结果存储在一个名为$msg的变量中,以避免连续两行解析相同的东西。