简体   繁体   中英

HTML5 how to get the id of the object that is clicked on?

I have a list of canvas like this:

<div id="lists" style="position:absolute">
        <ul>
            <li>
                <canvas id="product1" class="product" width="1200" height="360"></canvas>
            </li>
            <li>
                <canvas id="product2" class="product" width="1200" height="360"></canvas>
            </li>
            <li>
                <canvas id="product3" class="product" width="1200" height="360"></canvas>
            </li>
            <li>
                <canvas id="product4" class="product" width="1200" height="360"></canvas>
            </li>
            <li>
                <canvas id="product5" class="product" width="1200" height="360"></canvas>
            </li>
        </ul>
    </div>

I want to write a event listeners for all the five canvass:

$(".product").mousedown(function(e) {

}

I want to know which canvas the user clicked on in the event handler. Is there a way to know that? If I write five event handler for the five canvases, the code will be too ugly.

The answer is in the event object and the context of which it is called, those are parsed with the callback function. You can look at $(this) or http://api.jquery.com/event.target/ .

$(".product").mousedown(function(e) {
    alert($(this).attr('id'));
});

Will give you the 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