javascript - getElementsByClassName 与 getElementById 不同(支持浏览器)

标签 javascript jquery dom event-handling jquery-events

有效的脚本:

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 as "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);
});

最佳答案

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

您必须循环访问返回的元素并对代码进行相关修改以适应这一点。

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

关于javascript - getElementsByClassName 与 getElementById 不同(支持浏览器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27697457/

相关文章:

javascript - 在句子中找到一个定义长度的数字并解析它

javascript - 向列表添加删除按钮

javascript - 为什么 `Object.prototype.toString` 总是返回 `[object *]` ?

jquery - 输入字段在追加时更改大小

javascript - 将数字与小数连接并转换回 int 的正确方法是什么?

jquery - mousemove 事件仅在 mousedown 后更新一次

javascript - Mozilla Firefox 不在 addEventListener ('load' 中加载 SVG 对象

asp.net - ASP :HyperLink is not rendered on browser

javascript - 使用特定浏览器的弹出窗口

javascript - JavaScript 函数中出现意外类型错误