首页 > 解决方案 > 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>

标签: javascriptjqueryhtml

解决方案


我认为你应该听输入元素而不是#button。你应该得到 id.attr()

$(document).ready(function(){
        $('#button input').click(function(){
            var x = $(this).attr("id");
            player(x);
        });
    });

推荐阅读