当event.target是XMLHttpRequest时,获取活动的DOM元素

时间:2011-07-21 18:17:58

标签: javascript ajax dom

我需要获取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);
    }
};

1 个答案:

答案 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