Home >Web Front-end >JS Tutorial >Analyze how to get the ID name of the current button or html

Analyze how to get the ID name of the current button or html

巴扎黑
巴扎黑Original
2017-06-23 10:07:231955browse

What I did today is upload a picture, click on the picture to delete it.

Randomly give the picture id, get the picture id, and then delete the picture.

Since the image ID is random, clicking on the img or clicking on the class will not work to get the ID. Finally, use the onclick event to obtain it.

The js code is as follows:

$("#pic").append("<img style=&#39;width:70px;margin:5px;height:70px;&#39; id=&#39;"+num+"&#39; onclick=&#39;upimg()&#39; src=\"" + images.localId + "\" />");

Start getting it like this:

    function upimg(){var id= $(this).attr("id");
        alert(id);
        }

No. Later I used:

    function upimg(){
        alert(event.target.id);
        }

to get it.

Summary:

Try to use event.target.id, do not use this. id.
When using event delegation, this points to the element bound to listen for the event, not the clicked element. event.target.id always points to the clicked element

The above is the detailed content of Analyze how to get the ID name of the current button or html. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn