簡體   English   中英

保存狀態單選按鈕javascript-html

[英]Save state radio button javascript-html

我正在嘗試一個保存單選按鈕狀態並檢查它的程序。 這是我的代碼,但我不知道它的錯誤。 請幫幫我

<script>
function saveState(){
   var ans1 = document.getElementById('grupo1');
   if (ans1.value == 1)
   {
       ans1.setAttribute("checked","checked");
       ans1.checked = true;
   }
</script>

<input type="radio" name="group" id="grupo1" value="1"> One
<input type="radio" name="group" id="grupo2" value="0"> Two
<input type="submit" onclick="saveState()" value="update">

嘗試這個:

<script>
    function saveState(){
        var ans1 = document.querySelector('input[name="group"]:checked').value;

        if (ans1.value == 1){
              ans1.setAttribute("checked","checked");
              ans1.checked = true;
        }
   }
  </script>

你或許這意味着什么?

除非grupo1按鈕可以更改值,否則您的代碼沒有多大意義

以下腳本假定您在某處具有標准cookie腳本

<script>
window.onload=function() {
  if (getCookie("grupo1")=="true") {
   document.getElementById('grupo1').click(); 
  }
  // either this
  document.getElementById('grupo1').onclick=function() {
     setCookie("grupo1","true")
  }
  // or this - depending on when you want to save the state
  document.getElementById("form1").onsubmit=function() {
    setCookie("grupo1",document.getElementById('grupo1').checked?"true":"false");
  }
}
</script>
<form id="form1">
<input type="radio" name="group" id="grupo1" value="1"> One
<input type="radio" name="group" id="grupo2" value="0"> Two
<input type="submit" value="update">
</form>

在你的方法中放置括號有助於防止像這樣的情況。

例如,如果將開括號放在與條件本身相同的行上的函數,循環,條件(if)語句等(就像你在函數聲明中所做的那樣),你只需要查找關閉的。

另一方面,如果將開始和結束括號放在它們自己的行上,則代碼將更加垂直對稱,這使得在處理更大的代碼塊時更容易發現缺少的括號。

您應該查看這篇涉及此特定問題的文章: http//encosia.com/in-javascript-curly-brace-placement-matters-an-example/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM