getZX = function(e) {
var dad = e.parentNode;
var index = e.dataset.idx;
var URL = dad.childNodes[1].childNodes[0].href + '/log';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var temp = document.createElement('div');
temp.innerHTML = xmlhttp.responseText;
var user = temp.querySelector('#zh-question-log-list-wrap');
var user0 = user.children[user.children.length - 1].children[0].outerHTML;
var time = user.querySelector('time').innerHTML;
var id = 'div' + index;
var dive = document.createElement('div');
dive.setAttribute('id', id);
dive.innerHTML = time;
dive.innerHTML += user0;
e.outerHTML = dive.outerHTML
}
}
xmlhttp.open('GET', URL, true);
xmlhttp.send()
}
window.onload=function(){
var script = document.createElement("script");
script.appendChild(document.createTextNode(""));
script.setAttribute("type","text/javascript");
document.head.appendChild(script);
var AJAXs = document.getElementsByClassName('HotItem'),btn;
var len=2//AJAXs.length;
//添加所有btn
for (let i = len-1; i >=0; i--) {
btn = document.createElement('input');
btn.setAttribute("data-idx",i);
btn.setAttribute("type","button");
btn.setAttribute("value",(i+1) +"_獲取資訊");
btn.setAttribute("onclick","getZX(this)");
AJAXs[i].appendChild(btn);
}
}
这是我的代码,功能是在知乎的热榜这个页面,为每个问题引入一按钮,可查看每个问题的时间等资讯。最让我不懂的地方是,我的这个getZX函数,用作全局变量时,一切正常;可是倘若想把它存入script标签并引入网页的head里面(代码会压成一行,同时把各种引号嵌套的问题解决掉,这些我考虑到了),就会一串报错,而且报错的理由我也看不懂。点击按钮会提示函数 is not defined。
有没有大神愿意不吝指点小人一二?