jquery - 使用 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>
解决方案
您可以使用以下代码代替 $(this).attr("value")。
var userBtnValue = ($(this).val());
你在 Chrome 上吃过这段代码吗?
推荐阅读
- javascript - 尽管在组件内调用了 .catch,为什么没有作为道具传递的承诺
- android - 如何在 Y 轴上平移 SurfaceView 或为其设置负边距?
- macos - SwiftUI:在最小值和最大值之间改变值的放大手势
- c# - LINQ 将数组与 DataRow 中的另一个数组匹配
- javascript - 我可以使用 javascript 在我的 html 文档中抓取其他网站吗?
- javascript - 简单的香草 JS 游戏
- python - 具有嵌套循环的理解列表中的迭代计数器
- javascript - Puppeteer 无法拦截 xhr 响应 json
- javascript - 触摸图像时如何使用javascript检测右键单击
- java - 合并多个 SDK