我的 html 页面脚本部分中的 teo 行是这些......
var mySession = sessionStorage.getItem("catProfile");
var myValue = mySession.getElementByID("catAge");
mySession 变量正确返回存储的字符串,该字符串是较大元素的内部 html。存储/检索的变量看起来像这样...你可以看到 ID catAge 存在,但是 myValue 变量出错,没有找到它,我是否使用了错误的技术?任何帮助表示赞赏。
<img class="profile-photo" src="/images/cats/vimes.webp">
<img class="care-icon" src="" <="">
<p class="name">Sir Vimes</p>
<p id="catAge" class="age">3 años</p>
<div class="details">
<img class="photo-one" src="/images/cats/vimes_one.webp" loading="lazy">
<img class="photo-two" src="/images/cats/vimes_two.webp" loading="lazy">
<img class="photo-three" src="/images/cats/vimes_three.webp" loading="lazy">
<p class="title">Beautiful, Playful and Affectionate Calico</p>
<p class="story">
This cat was found by the side of the street in a cardboard box,
she was hungry and wet from being in the rain. She has a wonderful
personalty, is friendly and loving.
</p>
<p class="health">No health issues</p>
<p class="gender">Female</p>
<p class="fee">$50.000 COP</p>
<p class="cuddle-factor">3</p>
<p class="activity-factor">7</p>
<p class="cat-friendly">yes</p>
<p class="dog-friendly">no</p>
</div>
因为
mySession
是一个字符串。 该字符串包含 HTML 代码,但就 JavaScript 而言它仍然只是一个字符串。
一种方法可能是创建一个元素来包装该 HTML 代码,向其中添加 HTML 代码,然后查询该元素。 例如:
// fetch string from storage
var mySession = sessionStorage.getItem("catProfile");
// create element
var myElement = document.createElement('div');
// add string to element as inner HTML
myElement.innerHTML = mySession;
// get the element you want from that in-memory element
var myValue = myElement.querySelector("#catAge");