从URL获取HTML内容后,如何使用JavaScript更改该内容

4
我正在使用 JavaScript 代码从页面中获取 HTML 内容,同时我也想修改从 HTML 中获取的内容(在 carttitle ID 内)。如何动态更改下面 cartbox.html 中 id=carttitle 的值?
这是代码(包含 HTML 的 div):
<!-- index.html -->
<!-- button to trigger the function -->
<button onclick="getcontent('cartbox.html','#cartboxes','#cartbox');">getcontent</button> <!-- the cartbox.html will fill the content below -->
<ul class="cartboxes" id="cartboxes">

</ul>

这是获取HTML的JavaScript代码函数。
// select.js
function getcontent(url, from, to) {
  var cached = sessionStorage[url];
  if (!from) {
    from = "body";
  } // default to grabbing body tag
  if (to && to.split) {
    to = document.querySelector(to);
  } // a string TO turns into an element
  if (!to) {
    to = document.querySelector(from);
  } // default re-using the source elm as the target elm
  if (cached) {
    return to.innerHTML = cached;
  } // cache responses for instant re-use re-use

  var XHRt = new XMLHttpRequest; // new ajax
  XHRt.responseType = 'document'; // ajax2 context and onload() event
  XHRt.onload = function() {
    sessionStorage[url] = to.innerHTML = XHRt.response.querySelector(from).innerHTML;
  };
  XHRt.open("GET", url, true);
  XHRt.send();
  return XHRt;
}

这是我将从中获取内容的HTML代码。
<!-- cartbox.html -->
<div id="cartbox">
  <li>
    <div class="cartbox">
      <div class="cartboxleft">
        <img src="img/search.png" width="60px" height="60px">
      </div>
      <div class="cartboxright">
        <!-- i want to change the value of the carttitle below dynamically -->
        <b class="carttitle" id="carttitle">nice Pizza</b>
        <p class="cartdescription">Number: <b>1</b></p>
        <p class="cartdescription">Price: <b>$ 11.22</b></p>
      </div>
      <div class="cartboxdelete">
        <button class="deletebutton" onclick="deleteitem(this);">X</button>
      </div>
    </div>
  </li>
</div>

你想要更改文本“好吃的披萨”吗? - devlin carnate
是的,我想通过Javascript动态更改内容。 - al de
那么,是什么阻止你使用getElementById并更改文本呢? - devlin carnate
我应该把getElementById放在哪里? - al de
2个回答

0

你应该使用 responseType = 'text',因为不建议使用 document responseType,以避免浪费时间无用地解析 HTML。现在关于你的问题,你可以这样做:

function getcontent(url, fromSelector, toSelector) {
    var cached = sessionStorage[url];
    if (cached) {
        return toSelector.innerHTML = cached;
    }

    fromSelector = fromSelector || 'body';
    toSelector = toSelector && document.querySelector(toSelector) || document.querySelector(fromSelector);

    var XHRt = new XMLHttpRequest();
    XHRt.open("GET", url, true);

    XHRt.responseType = 'text';
    XHRt.onload = function() {
        if (XHRt.readyState === XHRt.DONE && XHRt.status === 200) {
            toSelector.innerHTML = XHRt.responseText;
            document.getElementById('carttitle').innerHTML = 'your new value';
            sessionStorage[url] = toSelector.innerHTML; // Now it will work after loading from session storage.
        }
    };

    XHRt.send();
}

这是一个很好的答案,只有一件事情,当我首次触发函数时,carttitle的值会改变,但之后它会返回到“美味比萨”。 - al de

0

你的缓存处理无法工作,因为你正在使用方括号运算符[]选择会话存储对象中的属性。相反,请使用{{link1:getItem()}}方法获取你要查找的键。

var cached = sessionStorage.getItem(url);

在你的第二个if语句中,你检查了toto.split。除非to字符串有一个split属性,否则这将失败。你的意图似乎不明确。相反,只需检查该字符串是否为有效字符串即可。
if (to && 'string' === typeof to) {

在创建 XMLHttpRequest 的新实例时,会失败因为你缺少调用构造函数的括号。
var XHRt = new XMLHttpRequest();

然后在你的onload回调函数中,你需要使用setItem()方法将结果的innerHTML保存到会话存储中。

但在此之前,使用querySelector选择购物车标题元素,并根据需要更改元素内容。

XHRt.onload = function() {
  let element = this.response.querySelector(from);
  if (element !== null) {
    let cartTitle = element.querySelector('#carttitle');
    cartTitle.textContent = 'An even better pizza';
    let html = element.innerHTML;
    to.innerHTML = html;
    sessionStorage.setItem(url, html);
  }
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接