This question already has answers here:
JavaScript property access: dot notation vs. brackets?
                                
                                    (13个回答)
                                
                        
                        
                            How to get the data-id attribute?
                                
                                    (13个回答)
                                
                        
                                在10个月前关闭。
            
                    
我正在学习使用JavaScript,并且每次点击后都尝试在“ bruh”和“ moment”之间交替显示一些文字。我正在尝试将文本的状态存储在属性“数据状态”中(应在1和2之间交替显示),但是在第12行上出现“未捕获的ReferenceError:赋值无效的左侧”。

<html>
<head>
    <title>bruh moment</title>
    <style type="text/css">
        * {text-align: center; color: blue;}
    </style>
    <script type="text/javascript">
        function funcClick(){
            var myParagraph = document.getElementById("myp");
            if (myParagraph.data-state == 1){
                myParagraph.innerHTML = "bruh";
                myParagraph.data-state = 2; //ERROR IS HERE
            }else{
                myParagraph.innerHTML = "click again i dare you";
                myParagraph.data-state = 1;
            };
        };
    </script>
</head>

<body>
    <p id="myp"; data-state=1;> bruh </p>
    <button type="button" onclick="funcClick()">
        Click me
    </button>

</body>
</html>



  预期:
  点击按钮->“时刻”
  点击按钮->“ bruh”
  点击按钮->“时刻”
  点击按钮->“ bruh”
  
  实际:
  [Uncaught ReferenceError:分配中的左侧无效]
  点击按钮->“ bruh”
  [未捕获的ReferenceError:未定义funcClick]
  点击按钮->“ bruh”
  [未捕获的ReferenceError:未定义funcClick]


这是实际的网页,以防http://3863.us/

最佳答案

变量名称中不能包含连字符--使用[]括号:

myParagraph["data-state"] = 2;

09-27 09:14