我正在尝试设计一个简单的子手游戏,并有一排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>

最佳答案

只需使用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!!!");
    }
});

09-16 16:33