我结合了XHR-get的两个概念(它从web组件中的属性获取JSON URL(,并将JSON数据显示为列表。一切都很好。
但是,当我想打开/关闭列表时,查询选择器All不起作用。但它确实可以在浏览器控制台中工作。
也许是因为在连接回调中,DOM尚未呈现,因此无法编辑?我尝试过渲染回调/渲染/设置超时,但没有任何效果。还尝试了2个connectedCallback函数,但查询选择器仍然没有检测到JSON列表。
在浏览器控制台中,document.querySelectorAll('.history list'(工作正常。我该怎么做才能让它发挥作用。非常感谢。
这是代码:
connectedCallback(){
let lock_time_ul = document.querySelector('#lock-time-ul');
// fetch data from JSON file (WORKING)
// fetch JSON URL value (ONLY if attribute has been set)
if (this.hasAttribute('json-url'))
{
this.json_url = this.getAttribute('json-url');
// fetch data from this URL
const xhr = new XMLHttpRequest();
xhr.open('GET', this.json_url);
xhr.onload = function(){
this.json_output = JSON.parse(xhr.response);
// (WORKING FINE)
this.json_output.forEach(el => {
// change el.type from enrollment -> locked and cancellation -> unlocked
if (el.type == "enrollment")
{
el.type = "Locked";
}
else if(el.type == "cancellation")
{
el.type = "Unlocked";
}
var li = document.createElement('li');
var span = document.createElement('span');
span.className = "date";
li.className = "history-list";
span.appendChild(document.createTextNode(el.date));
var div_lock_wrapper = document.createElement('div');
div_lock_wrapper.className = "lock-wrapper";
div_lock_wrapper.style.fontWeight = 500;
div_lock_wrapper.appendChild(document.createTextNode(el.type));
li.appendChild(span);
li.appendChild(div_lock_wrapper);
lock_time_ul.appendChild(li);
})
}
xhr.send();
}
// javascript for sidebar show / hide (NOT WORKING, QUERY SELECTOR ALL history-list SHOWS NULL)
let toggle_lock_history_btn = document.querySelector(".history-title");
let toggle_lock_history_list = document.querySelectorAll(".history-list");
let toggle_show_all_text = document.querySelector(".show-all");
toggle_lock_history_btn.addEventListener('click', function()
{
// check the history-title first
if (toggle_lock_history_btn.textContent == "Hide lock history")
{
// toggle off
toggle_lock_history_list.forEach(el => {
el.style.display = "none";
})
// hide show-all
toggle_show_all_text.style.display = "none";
// change Hide to Show in history-title
toggle_lock_history_btn.textContent = "Show lock history";
}
else if (toggle_lock_history_btn.textContent == "Show lock history")
{
// toggle on
toggle_lock_history_list.forEach(el => {
el.style.display = "";
})
// show show-all
toggle_show_all_text.style.display = "";
// change Show to Hide in history-title
toggle_lock_history_btn.textContent = "Hide lock history";
}
})
} // connectedCallback ENDS
我的HTML
<test json-url="data.json"></test>
得到了解决方案:
window.onload = init;
function init(){
// the code to be called when the dom has loaded
}
因为我试图通过ID获取的元素是动态创建的(由ajax加载并由脚本创建(。