我正在尝试设计一个简单的刽子手游戏,并且有一行div元素,其中id为字母。我想收到被点击的元素的id,似乎无法弄明白。
<script>
var guesses = 5;
var word = "hangman";
var spotsLeft = 7;
$(document).ready(function(){
$(".letter").click(function(){
$(this).hide();
guesses--;
if(//Psuedo-code -- if a specific letter is clicked (based on element id)
$("#guessesLeft").html("You have " + guesses + " Guesses Left");
if(guesses == 0){
$("#guessesLeft").html("You are out of guesses, YOU LOST!!!");
}
});
});
</script>
答案 0 :(得分:5)
只需使用attr
函数即可获取所点击元素的id
属性。
$(".letter").click(function(){
$(this).hide();
var id = $(this).attr('id');
guesses--;
if(//Psuedo-code -- if a specific letter is clicked (based on element id)
$("#guessesLeft").html("You have " + guesses + " Guesses Left");
if(guesses == 0){
$("#guessesLeft").html("You are out of guesses, YOU LOST!!!");
}
});
答案 1 :(得分:1)
使用.attr()
获取元素属性的值。具体来说,使用:
$(".letter").click(function() {
let letterId = $(this).attr('id');
...
});
答案 2 :(得分:1)
另外两个答案是正确的,但我只是向他们添加JS:
只有Javascript: 首先你需要编辑你的元素,让我们说它是这样的:
<button class=".letter" onClick="getId(this.id)">Click Me!</button>
<script type="text/javascript">
function getId(clicked_id)
{
alert(clicked_id);
}
</script>
JQuery:
var id = $(this).attr('id');