我正在使用 JavaScript 代码从页面中获取 HTML 内容,同时我也想修改从 HTML 中获取的内容(在 carttitle ID 内)。如何动态更改下面 cartbox.html 中 id=carttitle 的值?
这是代码(包含 HTML 的 div):
这是获取HTML的JavaScript代码函数。
这是我将从中获取内容的HTML代码。
这是代码(包含 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>