简体   繁体   中英

JQuery: get object inside span

I am very new to jQuery. Below is part of my code

<div class = 'buttons'>
    <span>
    <input type='button' value='BUTTON1' id='button1'>
    </span>
    <span>
    <input type='button' value='BUTTON2' id='button2'>
    </span>
</div>

Using jquery, I would like to print the id of the button clicked. I tried the following:

$(".buttons > span").click(function () {
    alert("YOU CLICKED" + this.id);
});

But I think this is referring to the span object. This is weird because how come the span object has a click event? Or all jquery objects have "click"? How do I get the id of the button in the span?

Thank You.

Here is another way to do that by capturing the event's target element:

$(".buttons > span").click(function (e) { 
    alert("YOU CLICKED" + e.target.id); 
}); 

What about this?

$(".buttons > span > input").click(function () {
    alert("YOU CLICKED" + this.id);
});
$(".buttons > span").click(function () {
    alert("YOU CLICKED" + $('input[type=button]',this).prop('id'));
 });

or you could bind the event to the button itself

$(".buttons > span > input[type=button]").click(function () {
    alert("YOU CLICKED" + this.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