尝试捕获jQuery中选择了哪个按钮

时间:2018-09-25 14:32:38

标签: javascript jquery html css

我试图捕获用户为简单的琐事游戏单击的按钮。我的代码似乎在“新游戏按钮”功能之后立即中断。当我console.log(userInput)单击相应的按钮后,没有任何显示。如何存储在变量userInput中单击的按钮的值?

<div class="gameInfo">
  <div class="timeRemaining"></div>
  <div class="question">question</div>
  <div class="answers">
    <button id="button1" value="Number 1">Button 1</button><br>
    <button id="button2" value="Number 2">Button 2</button><br>
    <button id="button3" value="Number 3">Button 3</button><br>
    <button id="button4" value="Number 4">Button 4</button>
  </div>
</div>
  $("#newGameButton").click(function() {
    alert("You started a new game!");
    $("#newGameButton").hide();
    $(".gameInfo").show();
    $(".results").show();
    askQuestions();
    assignButtons();
  })

  $("#button1", "#button2", "#button3", "#button4").click(function() {
    var userInput = $(this).val();
    console.log(userInput);
  })
})

1 个答案:

答案 0 :(得分:4)

您的选择器无效。看来您正在尝试将#buttonN元素添加到单个jQuery对象中,在这种情况下,您需要为字符串提供一个单个字符串。 jQuery对象,如下所示:

$("#button1, #button2, #button3, #button4").click(function() {
  var userInput = $(this).val();
  console.log(userInput);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="button1" value="Number 1">#1</button>
<button id="button2" value="Number 2">#2</button>
<button id="button3" value="Number 3">#3</button>
<button id="button4" value="Number 4">#4</button>

不过,您应该注意,通用类会使此选择器更好,因为它具有更好的可扩展性。