为什么它会在分配中显示无效的左侧

Why will it say Invalid left-hand side in assignment?

本文关键字:无效 显示 分配 为什么      更新时间:2023-09-26

所以,最近我在做一个项目时发现了这个错误。它说作业中的左侧无效。这是我的 HTML:

<section><input type="button" value="Activate radar jamming" onclick="jam()"></section>

这是我的Javascript:

function jam() {
    document.getElementById("jam")=Math.random();
    if(jam < 0.350) {
       console.log(jam)
       location.reload();
    }
}

请帮助我。谢谢。

为什么在作业中会显示无效的左侧?

因为赋值的左侧不能是函数调用。它必须是变量或属性。

您的jam函数也存在问题。您正在分配给符号 jam ,但您没有将其声明为函数中的变量,因此您分配给的实际上是函数本身(因为它被称为 jam )。

修复这两个问题:

function jam() {
    var jamValue = Math.random();                    // Note the variable
    document.getElementById("jam").value = jamValue; // Note the .value
    if(jamValue < 0.350) {
        console.log(jamValue)
        location.reload(); // It's unclear to me whether this should be in the `if`
    }
}

这假定具有id "jam"的元素是input元素。如果没有,请将.value更改为 .innerHTML

将随机值设置为元素"值":

document.getElementById("jam").value = Math.random();