我正在尝试使用 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。您应该使用 .attr()
$(document).ready(function(){
$('#button input').click(function(){
var x = $(this).attr("id");
player(x);
});
});
关于javascript - jQuery 无法从 $(this) 按钮单击获取 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51100292/