jQuery无法从$(this)按钮单击

时间:2018-06-29 11:04:12

标签: javascript jquery html

我正在尝试使用jQuerythis)来单击按钮的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>

5 个答案:

答案 0 :(得分:2)

我认为您应该听输入元素而不是#button。并且您应该获得.attr()

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

答案 1 :(得分:0)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<title>QuizMaster</title>
<head>
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
	function player(x){
		var player = x;
		console.log(player);
	}

	$(document).ready(function(){
		$('input[type="button"]').click(function(){
			var x = $(this).attr('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>

答案 2 :(得分:0)

您应该这样使用

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

答案 3 :(得分:0)

也许像这样:

	function player(x){
		var player = x;
		console.log(player);
	}

	$(document).ready(function(){
		$('#button :button').click(function(){
			var x = $(this).attr('id');
			player(x);
		});
	});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>


<form id="button">
		<input type="button" id="eset" value="Reset">
		<input type="button" id="player1" value="Player1">
		<input type="button" id="player2" value="Player2">
</form>

答案 4 :(得分:0)

您可能仅引用event.target元素即可获得 id 。此外,您无需将 this 关键字转换为jQuery对象,然后应用 .attr 方法:缩写为:this.id。

摘要:

$(document).ready(function(){
  $('#button').on('click', function(e){
    var x = e.target.id;
    console.log('button pressed is: ' + x);
  });
});  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<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>