javascript - 单击按钮时将变量从 html 传递到 Javascript Format If 语句

标签 javascript html

我试图在 html 页面上放置按钮,并使用 javascript 中的 if 语句格式化我的输出,但我无法让它工作,我要么同时得到(不能正确),要么(两者都没有)我已将此处的代码格式化为例如,它不起作用,但希望您能够理解并回答我的查询。

<script type="text/javascript">
  function handleIt(n){
    if (n = "A"){alert("A");}
    if (n = "D"){alert("D");}
  }
</script>
</head>
<body>
<h1>Admin Control panel :</h1>
   <button type="button"id="A"onclick="handleIt(n)">+</button>
   <button type="button"id="D"onclick="handleIt("D")">-</button>

最佳答案

您有几个问题,

if (n = "A"){ } 
//as Will pointed out
//this statement represents assignment which is always TRUE
//but in your case, it's equality(i hope) which can be TRUE or FALSE depended on your both variables

<button type="button"id="D"onclick="handleIt("D")">-</button> 
<!--onclick is written incorrect, use single quotes instead, "handleIt('D')"-->

下面是工作示例

<script type="text/javascript">
  function handleIt(n){
    if (n == "A"){ alert("A"); }
    if (n == "D"){ alert("D"); }
  }
</script>
<button type="button" id="A" onclick="handleIt('A')">+</button>
<button type="button" id="D" onclick="handleIt('D')">-</button>

关于javascript - 单击按钮时将变量从 html 传递到 Javascript Format If 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35325105/

相关文章:

javascript - 通过 jquery 将 attr href 更改为其他内容。这一切有什么影响

javascript - React-Router RouteHandler 未定义

javascript - 倒计时达到 0 时发出蜂鸣声

javascript - 如何停止 CSS3 过渡

html - 溢出隐藏设置在 IE 11、Firefox 中不起作用

javascript - 如何使用 $scope 和 ng-bind 检索 AngularJS 中的文本框条目

javascript - 如何将两个数组连接成一个二维数组?

javascript - 单击按钮将值传递给 jquery 函数

html - 当 nth-child() 在页面之间变化时指定 CSS

html - rtl HTML 页面中的方向 ltr