【问题标题】:querySelector, getElementById on div Inner HTML not workingdiv内部HTML上的querySelector,getElementById不起作用
【发布时间】:2020-07-16 05:04:20
【问题描述】:

假设我有一个带有导航栏的 ejs 文件,其中包含类的 a-tags。每当单击每个 a-tags 时,我都会向服务器发出 http 请求,该服务器使用 html 代码响应,然后我将其设置为 div 的 innerHTMl。我面临的问题是我不能不做任何查询选择器,不能获取元素,甚至不能在响应 HTML 代码的 html 元素上做一个事件监听器。有没有办法让它工作,因为我真的需要这些工作。

我使用的外部 javascript 文件如下:

    var arr = this.id.split('-')
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
     if (this.readyState == 4 && this.status == 200) {
        // Typical action to be performed when the document is ready:
        document.querySelector('#nav-' + arr[1] + "-" + arr[2]).innerHTML = xhttp.responseText;
     }
 };
     xhttp.open("GET", "/basic" + arr[1] + "-" + arr[2], true);
     xhttp.send();
 })

【问题讨论】:

  • status 200 和 readyState 4?有错误吗?
  • 是的,上面的代码可以工作,只是我不能对 innerHTML 或 div 中的元素执行任何查询选择器甚至侦听器。好像他们不在那里
  • xhttp 在那里不可用。这是因为函数的范围。使用硬编码字符串再试一次,看看是否有更新作为健全性检查。或使用this.responseText
  • 更新部分起作用了,它实际上将所选div的innerHTML设置为请求的响应文本。
  • 我从这里得到了例子w3schools.com/xml/xml_http.asp

标签: javascript html jquery django express


【解决方案1】:

回顾一下我们的谈话,这里有一个例子可以比较。虽然要回答为什么我们不能使用xhttp.responseText 的问题,但该值在函数范围内不可用。令人担忧的是https://www.w3schools.com/xml/xml_http.asp 此处的实时示例显示使用xhttp,但随后他们的实时示例使用thisthis 分配给 XMLResponse 对象。不知道为什么……

<!DOCTYPE html>
<html>

<body>

    <h2>Using the XMLHttpRequest Object and fetch example</h2>
    <script>

        const URL = 'https://httpbin.org/get';

        function fetchExample() {
            let result = fetch(URL, { method: 'GET'});
            result.then((response) => {
                response.json().then((body) => {
                    document.querySelector("#demo").innerHTML = JSON.stringify(body); 
                });
            });
        }

        function loadXMLDoc() {
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200) {
                    document.querySelector("#demo").innerHTML = this.responseText;
                }
            };
            xhttp.open("GET", URL, true);
            xhttp.send();
        }

    </script>

    <div id="demo">
        <button type="button" onclick="loadXMLDoc()">Change Content using XMLRequest</button>
        <button type="button" onclick="fetchExample()">Change Content using fetch</button>
    </div>

</body>

</html>

这是我在这里找到的一个更有意义的示例 https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/response#Example

var url = 'somePage.html'; //A local page

function load(url, callback) {
  var xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
      callback(xhr.response);
    }
  }

  xhr.open('GET', url, true);
  xhr.send('');
}
load("https://httpbin.org/get", console.log)

回应

{
  "args": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate, br", 
    "Accept-Language": "en-US,en;q=0.9", 
    "Host": "httpbin.org", 
    "Origin": "https://developer.mozilla.org", 
    "Referer": "https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/response", 
    "Sec-Fetch-Dest": "empty", 
    "Sec-Fetch-Mode": "cors", 
    "Sec-Fetch-Site": "cross-site", 
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36", 
    "X-Amzn-Trace-Id": "Root=1-5f13bbc1-eaa2b0bc28697b24aca2db94"
  }, 
  "origin": "72.73.17.37", 
  "url": "https://httpbin.org/get"
}

【讨论】:

  • 除了选择或查询加载 html 页面中的任何元素外,似乎一切正常。
  • 什么是查询以及解析响应时 DOM 的内容是什么?似乎如果是这种情况,那么查询无效或当时 DOM 中不存在该元素。
  • @user8628552 你能让这个工作吗?如果我的回答有帮助,是否可以将其标记为正确以帮助其他人进行搜索?
  • 你能提供 DOM 和使用的查询吗?不是传递的参数化字符串而是文字字符串值?
【解决方案2】:

我结束了使用 axios 和 append 而不是 innerHTML,它工作正常

【讨论】:

    猜你喜欢
    • 2013-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-31
    • 2015-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多