简体   繁体   中英

How to get the element id of a div element that was clicked

I'm trying to design a simple hangman game, and have a line of div elements with the ids being letters. I want to receive the id of the element that is clicked, and can't seem to figure it out.

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

Just use the attr function to get the id attribute of the clicked element.

$(".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!!!");
    }
});

Use .attr() to get the value of an attribute for the element. Specifically, use:

$(".letter").click(function() {
    let letterId = $(this).attr('id');
    ...
});

The other two answers are correct but i am just adding JS to them :

Only Javascript : first you need to edit your element,lets say it was like this :

<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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM