有效的脚本:
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
时(相关元素同时具有 ID
和 Class
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/