[英]How to check if div has a specific value in JavaScript
I want to know how I can let the JavaScript react when the div has a certain value. 我想知道当div具有某个值时如何让JavaScript做出反应。
<div id="background">
<div id="value">1</div>
</div>
<script>
var text = document.getElementById("value");
if (text = "0") {
document.getElementById("background").style.backgroundColor="red";
}
</script>
If the value div has 0, I want the background color to be red of the div called background. 如果值div为0,则我希望背景色为div的红色,称为背景。 If the value div has a other value, it should do nothing. 如果值div具有其他值,则不应执行任何操作。 This is what I've come up to. 这就是我要提出的。 But it don't work. 但这不起作用。 Even if I put another value in the value div, the red background still shows. 即使我在值div中输入了另一个值,红色背景仍然显示。 Except when I emptied the value div, then ofcourse you will see nothing. 除非我清空div值,否则您什么都看不到。
var text = document.getElementById("value").innerHTML;
if (text == "0") {
...
The comparison operators in JavaScript are ==
and ===
, not =
(that one is always assignment ). JavaScript中的比较运算符是==
和===
,而不是=
(那个总是赋值 )。 So: 所以:
if (text == "0") {
or 要么
if (text === "0") {
You're also not getting the text correctly: 您也无法正确获取文本:
var text = document.getElementById("value");
That gives you the element , not its contents. 那给了你元素 ,而不是它的内容。 For contents, use innerHTML
. 对于内容,请使用innerHTML
。
var text = document.getElementById("value").innerHTML;
// Here -----------------------------------^
if you want to use jquery: 如果要使用jQuery:
if($("#value").html() == "0") {
$("#background").css("background-color", "red");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.