gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 15:30:07 25 4
gpt4 key购买 nike

有效的脚本:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com