在getElementById所做的事情中,getElementsByClassName不起作用(支持浏览器)

时间:2014-12-29 23:21:20

标签: javascript jquery dom javascript-events event-handling

有效的脚本:

function getEventTarget(e) {
    e = e || window.event;
    return e.target || e.srcElement; 
}
var ul = document.getElementById('commandList');
ul.onclick = function(event) {
    var target = $(getEventTarget(event)).clone().children().remove().end().text();
    document.getElementById('inputCommand').value = target;
};

var interface = '/cgi-bin/CGIProxy.fcgi?cmd=';
var protocol = 'http://';
var host, command, access, commandUrl;

$('.sendCommand').click(function() {
    host = $('#cameraLocation').val();
    access = $('#cameraAccess').val();
    command = $('#inputCommand').val() + $('#inputParam').val();
    commandUrl = protocol + host + interface + command + access;                
    $('#showUrl').html(commandUrl);
    $('#showResult').attr('src', commandUrl);
});

当我将document.getElementById更改为document.getElementsByClassName时(相关元素同时将IDClass设为"commandList"),脚本不会继续工作,我错过了什么?谢谢!

新脚本:

function getEventTarget(e) {
    e = e || window.event;
    return e.target || e.srcElement; 
    }
var ul = document.getElementsByClassName('commandList');
ul.onclick = function(event) {
    var target = $(getEventTarget(event)).clone().children().remove().end().text();
    document.getElementById('inputCommand').value = target;
    };

var interface = '/cgi-bin/CGIProxy.fcgi?cmd=';
var protocol = 'http://';
var host, command, access, commandUrl;

$('.sendCommand').click(function() {
    host = $('#cameraLocation').val();
    access = $('#cameraAccess').val();
    command = $('#inputCommand').val() + $('#inputParam').val();
    commandUrl = protocol + host + interface + command + access;                
    $('#showUrl').html(commandUrl);
    $('#showResult').attr('src', commandUrl);
});

2 个答案:

答案 0 :(得分:3)

getElementsByClassName()返回匹配元素的HTMLCollection,因为多个元素可以共享公共类属性。

您必须遍历返回的元素并对代码进行相关修改才能对此进行调整。

请参阅:https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName

答案 1 :(得分:1)

getElementsByClassName()返回元素的NodeList,而getElementById()(和querySelector())返回单个节点。

要对类似数组的NodeList进行操作,您必须迭代NodeList中包含的每个元素,并分别为每个元素指定操作;例如:

Array.prototype.forEach.call(document.getElementsByClassName('whatever'), function (elem) {
    elem.onclick = function () {
        // do stuff;
    }
});

或者:

Array.prototype.forEach.call(document.getElementsByClassName('whatever'), function (elem) {
    elem.addEventListener('click', functionToCallOnClick);
});