我需要获取clicked元素的属性值,但是我点击了一个ajax请求,在这种情况下,event.target是XMLHttpRequest而不是点击的DOM元素。如何在这种情况下获得点击的DOM元素?
// Parsing and makeup.
function showDescription(XMLObj){
var parser = new DOMParser(),
XMLDoc = XMLObj.responseText,
parsedXMLDoc = parser.parseFromString(XMLDoc, 'text/xml'),
eventTarget = event.target,
descContent = document.getElementById('description') ;
// Conditional actions.
};
};
// Create request.
function loadAsync(url, callback) {
var request;
if(window.XMLHttpRequest) {
request = new XMLHttpRequest();
request.open("GET", url, true);
request.send(null);
request.onreadystatechange = requestProcess;
} else if(window.ActiveXObject){
request = new ActiveXObject('Microsoft.XMLHTTP');
if (request) {
request.open("GET", url, true);
request.send(null);
request.onreadystatechange = requestProcess;
}
}
function requestProcess() {
if (request.readyState == 4) {
if (request.status == 200) {
if (typeof callback == 'function') {
callback(request)
}
}
}
};
};
// Define event listener for each menu element.
function showDescListener(){
var descPars = document.getElementById('description-paragraphs'),
descParLi = descPars.getElementsByTagName('li');
for (var i = 0; i < descParLi.length; i++){
descParLi[i].addEventListener('click', function(event) {loadAsync('/description/', showDescription)}, false);
}
};
答案 0 :(得分:1)
更改
function showDescription(XMLObj){
到
function showDescription(XMLObj, target){
然后改变
descParLi[i].addEventListener('click', function(event) {loadAsync('/description/', showDescription)}, false);
到
descParLi[i].addEventListener('click', function(ev) {loadAsync('/description/', function(request) { showDescription(request, ev.target); })}, false);
然后在target
内使用showDescription
。
此更改捕获在闭包中单击按钮时的事件,然后在回调中使用该闭包。换句话说,请注意回调函数如何使用ev
参数 - 调用回调时保留ev
的值及其target
属性(DOM元素为然后将其传递到showDescription
。