0

This is my current code:

function tableClick(event){
    $('#table').click(function(event){
        alert(event.target.id);     
    });
}

<table id="table">
    <tr>
        <td id="td1" onclick="tableClick(this)">
            1
        </td>
    </tr>
    <tr>
        <td id="td2" onclick="tableClick(this)">
            2
        </td>
    </tr>
</table>

What I don't understand is why it pops up the alert window one more time than last. How can I fix this? Thanks in advance.

2 Answers 2

4

Each time you click, you call this function.

function tableClick(event){
    $('#table').click(function(event){
        alert(event.target.id);     
    });
}

This part:

$('#table').click(function(event){

attaches a click handler to the table. Every time you click you attach a new click handler to the table.

Sign up to request clarification or add additional context in comments.

Comments

1

Because you are attaching click handler on every click -

You can do this -

function tableClick(this){
     alert(this.id);     
}

1 Comment

Thank. But it seems this doesn't work. So I keep it as tableClick(event) {alert(event.id);} and it workds

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.