简体   繁体   English

JavaScript不响应复选框

[英]JavaScript not responding to checkboxes

I have a page with checkboxes that have string values (A, B, C). 我有一个带有复选框的页面,该复选框具有字符串值(A,B,C)。 I am trying to create an app that builds a string on the screen based on the values of the selected checkboxes, separated by the '+', for example 'A+B+C' or 'A+B', etc. 我正在尝试创建一个应用程序,该应用程序根据所选复选框的值在屏幕上构建字符串,并以'+'分隔,例如'A + B + C'或'A + B'等。

Yet, my div is not showing when the checkboxes are selected. 但是,当选中复选框时,我的div不会显示。

What am I doing wrong? 我究竟做错了什么?

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script> var arr = $(".offers:checked").map(function() { return $(this).val(); }).get(); $('#displayConcatenatedString').html(arr.join('+')); </script> <div id="displayConcatenatedString"></div> <table style="width:100%"> <tr> <th>1</th> <th>2</th> <th>3</th> </tr> <tr> <td><label><input type="checkbox" name="selected" value="A" class="offers" />A</label></td> <td><label><input type="checkbox" name="selected" value="B" class="offers" />B</label></td> <td><label><input type="checkbox" name="selected" value="C" class="offers" />C</label></td> </tr> </table> 

You need to run your code when the state changes. 当状态更改时,您需要运行代码。 Essentially your code is running once when the page loads, but you want to build your string whenever one of your checkboxes state changes. 本质上,页面加载时,代码只运行一次,但是只要复选框之一的状态发生更改,您就希望构建字符串。

The code below will run the code contained in your question every time one of the checkboxes is clicked (you could also use the change event). 每次单击其中一个复选框时,下面的代码将运行问题中包含的代码(您也可以使用change事件)。

$(".offers").on("click", function(){
  var arr = $(".offers:checked").map(function(){
  return $(this).val();
    }).get();
  $('#displayConcatenatedString').html(arr.join('+'));  
})

Also, your script my_jq.js , is included in the header of your page, which means it will run prior to any of the HTML being rendered. 另外,脚本my_jq.js包含在页面的标题中,这意味着它将在呈现任何HTML之前运行。 That means the click handler suggested above will never fire. 这意味着上面建议的点击处理程序将永远不会触发。 There are several ways you can handle that. 有几种方法可以解决这个问题。 One is to move the script to the bottom of the page. 一种是将脚本移到页面底部。

<body>
    ...stuff...
    <script src="my_jq.js" type="text/javascript"></script>  
</body>

And/or you can wrap the above script to load when the page is ready. 和/或您可以包装以上脚本以在页面准备好时加载。

$(function(){
  $(".offers").on("click", function(){
    var arr = $(".offers:checked").map(function(){
    return $(this).val();
      }).get();
    $('#displayConcatenatedString').html(arr.join('+'));  
  })
})

Another option would be a handler attached to the document, but this should be enough to get you going. 另一个选择是附加到文档的处理程序,但这足以使您前进。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM