javascript JS 改变元素的类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16628973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JS Change class of element
提问by Cody Smith
All I'm trying to do is toggle the class of an elements by ID when they are clicked on.
我要做的就是在单击元素时按 ID 切换元素的类。
<script>
function selectLoad(id)
{
if(document.getElementById(id).className == "load") {
document.getElementById(id).className = "loadSelected";
} else {
document.getElementById(id).className = "load";
}
}
</script>
<div class="load" id=" ... set by PHP per element ... " onclick="selectLoad(this)">
This returns an error...
这将返回一个错误...
Uncaught TypeError: Cannot read property 'className' of null
未捕获的类型错误:无法读取 null 的属性“className”
So I guess it doesn't like the conditional.
所以我想它不喜欢条件。
I'm new to JS and need help, thanks in advance.
我是 JS 新手,需要帮助,提前致谢。
回答by 6502
You are passing the dom element itself (using this
), not the id
.
您正在传递 dom 元素本身(使用this
),而不是id
.
You should change the code to
您应该将代码更改为
function selectLoad(element)
{
if (element.className == "load") {
element.className = "loadSelected";
} else {
element.className = "load";
}
}
回答by Rob Johnstone
I think you are passing an id that does not exist in the dom. Has the dom loaded before your javascript is executed? Move the script to the bottom of the page just before the closing html tag
我认为您正在传递一个在 dom 中不存在的 id。在执行 javascript 之前是否加载了 dom?将脚本移动到页面底部的 html 结束标记之前
EDIT: Following discussion in comments below the error is this line:
编辑:在错误下面的评论中讨论以下错误是这一行:
<div class="load" id=" ... set by PHP per element ... " onclick="selectLoad(this)">
it should read
它应该读
<div class="load" id=" ... set by PHP per element ... " onclick="selectLoad(this.id)">
回答by Gabriel Petrovay
Your code is not safe because you don't check if you have the DOM element with the given id
您的代码不安全,因为您没有检查是否具有给定的 DOM 元素 id
That is why you get the error: Cannot read property 'className' of null
这就是您收到错误的原因: Cannot read property 'className' of null
if(document.getElementById(id)) {
// ... do something and do not go further.
return;
}
And the problem is passing this
when you call selectLoad
. At this point, this
is the DOM element, not the string that yo expect: ... set by PHP per element ...
. So you have to change the code accordingly.
this
当你打电话时,问题就过去了selectLoad
。此时,this
是 DOM 元素,而不是您期望的字符串:... set by PHP per element ...
。所以你必须相应地更改代码。