-1

作为表单提交的一部分,我有一个如下的输入标记。

<input type=“checkbox” id=“allowcheatmode” name=allowCheatMode value=“NO” onchange=“allowCheatModes()”&gt;

以及 JS 函数中的 allowCheatModes

function allowCheatModes(){
   var x = document.getElementById(“allowcheatmode”).checked
   if (x) {
      document.getElementById(“allowcheatmode”).value = “YES”
   } else {
      document.getElementById(“allowcheatmode”).value = “NO”
   }

但是,当我allowcheatmode在表单提交后尝试打印变量时,这不起作用。我在这里做错了什么?

4

4 回答 4

1
于 2021-08-19T06:48:15.517 回答
0

你做错了两件事


第一件事

你把 if 放在函数外面,请把 if 放在函数里面

function allowCheatModes() {
...
}

用。。。来代替

function allowCheatModes() {
...
  if(x){
    ...
  }
}

第二件事

您使用的函数名称错误,您应该使用 getElementById,而不是 getElemenetById

document.getElemenetById

用。。。来代替

document.getElementById

下面是我调整的片段,你可以参考一下。

祝你有美好的一天 :)

function allowCheatModes(){
  var x = document.getElementById("allowcheatmode").checked;
  if (x) {
     document.getElementById("allowcheatmode").value = "YES"
  } else {
     document.getElementById("allowcheatmode").value = "NO"
  }
  console.log(document.getElementById("allowcheatmode").value);
}
<input type="checkbox" id="allowcheatmode" name="allowCheatMode" value="NO" onchange="allowCheatModes()">

于 2021-08-19T07:05:47.173 回答
0

尝试这个

function allowCheatModes(){
    var isChecked = document.getElementById("allowcheatmode").checked;

    if (isChecked) {
      document.getElementById("allowcheatmode").value = "YES";
    } else {
      document.getElementById("allowcheatmode").value = "NO";
    }
}
<input type="checkbox" id="allowcheatmode" name="allowCheatMode" value="NO" onchange="allowCheatModes()">

上面的代码将是有效的,因为您在 getElemenetById 中有错字(应该是 getElementById,而不是 getElemeNETById)。无论如何,在这种情况下你什么也看不到,因为 type="checkbox" 的输入没有视图。您可以添加一些 div 元素来改进您的代码:

function allowCheatModes(){
    var isChecked = document.getElementById("allowcheatmode").checked;
    
    document.getElementById("allowcheatmode-view").innerHTML = isChecked ? "YES" : "NO";
}
<input type="checkbox" id="allowcheatmode" name="allowCheatMode" onchange="allowCheatModes()">

<div id="allowcheatmode-view">NO</div>

PS: "condition ? ifTrue : ifFalse" 是三元运算符,"if" 的缩写形式

于 2021-08-19T06:58:15.183 回答
0

不应该是这样的:

function allowCheatModes(){
    var x = document.getElementById(“allowcheatmode”).checked
    if (x) {
        document.getElemenetById(“allowcheatmode”).value = “YES”
    } else {
         document.getElemenetById(“allowcheatmode”).value = “NO”
    }
}
于 2021-08-19T06:46:54.317 回答