我试图用onclick
运行任何按钮的功能class="stopMusic"
。我在Firebug中收到错误
document.getElementByClass不是函数
这是我的代码:
var stopMusicExt = document.getElementByClass("stopButton");
stopButton.onclick = function() {
var ta = document.getElementByClass("stopButton");
document['player'].stopMusicExt(ta.value);
ta.value = "";
};
你可能意味着document.getElementsByClassName()
(然后抓住结果节点列表中的第一个项目):
var stopMusicExt = document.getElementsByClassName("stopButton")[0];
stopButton.onclick = function() {
var ta = document.getElementsByClassName("stopButton")[0];
document['player'].stopMusicExt(ta.value);
ta.value = "";
};
您可能仍会收到错误消息
document.getElementsByClassName
不是一个功能
但是,在旧版浏览器中,如果您需要支持这些旧版浏览器,则可以提供回退实现。
正如其他人所说,你没有使用正确的功能名称,并且在所有浏览器中都不存在。
如果您需要使用document.getElementById()
对带有id的元素进行跨浏览器提取,那么我强烈建议您在所有浏览器中获得支持CSS3选择器的库。它将为您节省大量的开发时间,测试和错误修复。最简单的方法就是使用jQuery,因为它可以广泛使用,具有出色的文档,可以免费访问CDN,并且有一个很好的社区,可以回答问题。如果这看起来比您需要的更多,那么您可以获得Sizzle,它只是一个选择器库(它实际上是jQuery和其他内部的选择器引擎)。我已经在其他项目中单独使用它,它简单,高效且小巧。
如果要一次选择多个节点,可以采用多种不同的方式。如果你给他们所有相同的课程,你可以这样做:
var list = document.getElementsByClassName("myButton");
for (var i = 0; i < list.length; i++) {
// list[i] is a node with the desired class name
}
它将返回具有该类名的节点列表。
在Sizzle,它将是这样的:
var list = Sizzle(".myButton");
for (var i = 0; i < list.length; i++) {
// list[i] is a node with the desired class name
}
在jQuery中,它将是这样的:
$(".myButton").each(function(index, element) {
// element is a node with the desired class name
});
在Sizzle和jQuery中,您可以将多个类名放入选择器中,并使用更复杂和强大的选择器:
$(".myButton, .myInput, .homepage.gallery, #submitButton").each(function(index, element) {
// element is a node that matches the selector
});
在进入任何进一步的错误检查之前,请先检查一下
document.getElementsByClassName()本身。
仔细检查其getElements而不是getElement
它应该是getElementsByClassName
,而不是getElementByClass
。看到这个 - https://developer.mozilla.org/en/DOM/document.getElementsByClassName。
请注意,某些浏览器/版本可能不支持此功能。
你拼错了它,它应该是“getElementsByClassName”,
var objs = document.getElementsByClassName("stopButton");
var stopMusicExt = objs[0]; //retrieve the first node in the stack
//your remaining function goes down here..
document['player'].stopMusicExt(ta.value);
ta.value = "";
document.getElementsByClassName - 返回具有多个项的节点堆栈,因为CLASS属性用于分配给多个对象...
getElementByClass
不存在,可能你想使用getElementsByClassName
。但是,您可以使用替代方法(用于angular / vue / react ...模板)
function stop(ta) {
console.log(ta.value) // document['player'].stopMusicExt(ta.value);
ta.value='';
}
<input type="button" onclick="stop(this)" class="stopMusic" value='Stop 1'>
<input type="button" onclick="stop(this)" class="stopMusic" value='Stop 2'>
enter code here
var stopMusicExt = document.getElementByClass("stopButton").value;
stopButton.onclick = function() {
var ta = document.getElementByClass("stopButton");
document['player'].stopMusicExt(ta.value);
ta.value = "";
};
// .value will hold all data from class stopButton
document.querySelectorAll
运作良好,可以让您进一步缩小选择范围。
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll