【问题标题】:JQuery get/load cannot parse new DOMJQuery get/load 无法解析新的 DOM
【发布时间】:2017-08-01 16:46:48
【问题描述】:

我正在尝试通过 AJAX 加载另一个页面内容。它会加载内容,但我在解析新内容时遇到问题。

这是我的代码

  $.get(urlPath, function (content) {
                var newDom = $(content);
                var newTitle = newDom.find("title").text();
                console.log(newDom);
                console.log(newDom.find(CLASS.MAIN_CONTENT));
                console.log(newTitle);
                $(CLASS.MAIN_CONTENT).replaceWith(newDom.find(CLASS.MAIN_CONTENT));
            });

这不起作用,我从请求中获取了有效内容,但仍然无法从新 DOM 中获取任何元素 这是用$(content)解析的输出

这是内容console.log(content)的原始输出

可能有什么问题,为什么这不起作用?

【问题讨论】:

    标签: javascript jquery ajax dom


    【解决方案1】:

    首先,请注意使用$() 解析该HTML 会丢弃其中的一些内容,因为$() 期望解析正文内容,而不是完整的文档。因此,看起来应该嵌套在结构中的元素可能最终会出现在 jQuery 对象的顶层。例如:

    var content = $(
      "<!doctype html>" +
      "<html>" +
      "<head><title>Example</title></head>" +
      "<body>" +
      "<p>Hi there</p>" +
      "</body>" +
      "</html>"
    );
    console.log(content.length); // 2
    content.each(function() {
      console.log(this.tagName); // TITLE, P
    });
    &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

    find 看起来within jQuery 对象中的顶级元素,但不查看顶级元素本身,只查看它们的后代。如果与您的CLASS.MAIN_CONTENT 选择器匹配的元素位于顶层,则find 将找不到它。你会想要filter。如果它可能在任一位置,您需要findfilter 的组合:

    var mainContent = newDom.find(CLASS.MAIN_CONTENT).add(newDom.filter(CLASS.MAIN_CONTENT));
    

    【讨论】:

    • 感谢您的回答,在这种情况下如何解析新标题?我只需要将带有 CLASS.MAIN_CONTENT 选择器的新块添加到现有的 DOM 中,替换旧的
    • @HelloMufecayo:我不明白这个问题。您使用从filter(或find,或两者的组合)获得的jQuery 对象...?
    • 我使用了这个解决方案,效果很好stackoverflow.com/questions/30676999/…
    【解决方案2】:

    解决方案

     var newDom = $('<div></div>').append($.parseHTML(content));
                    document.title = newDom.find("title").text();
                    $(CLASS.MAIN_CONTENT).replaceWith(newDom.find(CLASS.MAIN_CONTENT));
    

    【讨论】:

      猜你喜欢
      • 2018-10-19
      • 2022-01-04
      • 1970-01-01
      • 2020-10-14
      • 2021-03-30
      • 2017-07-23
      • 2016-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多