提问者:小点点

使用jquery从按钮检索属性/值


我试图在用户点击每个按钮时从它检索一个属性/值,但是代码不工作。 (为了澄清,刚添加了html片段)

null

$(".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>

null


共1个答案

匿名用户

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

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

你在Chrome上吃了这个代码吗?