javascript - jQuery 无法从 $(this) 按钮单击获取 id
问题描述
我正在尝试使用jQuery
( this
) 来获取单击按钮的 id 并将该 id 传递给函数以执行某些操作。我有三个按钮都具有不同的 id 并且希望在$(this)
我学习它时使用它但无论我以何种方式尝试它都无法让它工作 这是代码
<html>
<title>QuizMaster</title>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="jquery-3.1.0.min.js"></script>
<script>
function player(x){
var player = x;
console.log(player);
}
$(document).ready(function(){
$('#button').click(function(){
var x = $(this).id;
player(x);
});
});
</script>
</head>
<body>
<form id='button'>
<input type='button' id='reset' value='Reset'>
<input type='button' id='player1' value='Player1'>
<input type='button' id='player2' value='Player2'>
</form>
</body>
<html>
解决方案
我认为你应该听输入元素而不是#button。你应该得到 id.attr()
$(document).ready(function(){
$('#button input').click(function(){
var x = $(this).attr("id");
player(x);
});
});
推荐阅读
- for-loop - 如何在向量的元素上运行 for 循环并在 for 循环内和 for 循环外更改 rust 中的向量?
- python - 我可以将旧 Python 3.6.3 中的软件包复制并粘贴到新安装的 Python 3.7.4 的 /Lib/site-packages 目录中吗?
- flutter - 如何在 Flutter Markdown 中定义图像的高度和宽度?
- android - 如何在firestore中更改Hashmap中的值?
- mapbox - mapbox 支持的国家地址列表
- javascript - 如何在 React 中显示来自 django-rest-framework 的错误消息
- javascript - 如何在 JavaScript 中将同步函数转换为异步函数
- python - 如何在 Tkinter Text 小部件中突出显示单词或字母?
- swift - 循环添加到 ContainerViews
- python-3.x - 如何强制 pip 直接从 Internet 而不是本地缓存安装包?