首页 > 解决方案 > 使用 jquery 从按钮中检索属性/值

问题描述

每当用户单击每个按钮但代码不起作用时,我都会尝试从每个按钮中检索属性/值。(只是添加了 html 片段以进行澄清)

$(".btn-choice").on("click", function() {

  console.log("You clicked a button!!");

  var userBtnValue = ($(this).attr("value"));
  userBtnValue = parseInt(userBtnValue);
  
  console.log(userBtnValue);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card mt-1">
  <div class="card-header">
    <div class="card-body text-center">
      <h3 class="card-title">You Pick</h3>
      <button id="button-1" class="btn btn-danger btn-choice" value="1">
        <h1>1</h1>
      </button>
      <button id="button-2" class="btn btn-danger btn-choice" value="2">
        <h1>2</h1>
      </button>
      <button id="button-3" class="btn btn-danger btn-choice" value="3">
        <h1>3</h1>
      </button>
      <button id="button-4" class="btn btn-danger btn-choice" value="4">
        <h1>4</h1>
      </button>
    </div>
  </div>

标签: jqueryeventsonclick

解决方案


您可以使用以下代码代替 $(this).attr("value")。

var userBtnValue = ($(this).val());

你在 Chrome 上吃过这段代码吗?


推荐阅读