jQuery event delegation

2019-01-05 06:23发布

I need some help with the callbacks. For some reason, they don't work really well.
I'm making a game with jQuery. I have a <div id='button'></div> for all the buttons that are going to be in the game. The game is going to have two buttons that make actions, and a question on top of it. The question is controlled by a <h3 id='text'></h3>. What I want to know, is that for some reason I can't set callback functions to the button's ID's. In example, I'd have the yes or no, that have their own id's set through jQuery like this:

$('#button').html('<button id='yes'>Yes</button><button id='no'></button>');
But for some reason, I would be able to set this:

$('yes').click(function(){
  //function I would want
});

Of course, that's not what my code has, that was just an example. Here's the real code:

$(document).ready(function(){
    $('#main,#batman,#car,#cop,#hobo,#knife,#gangfight,#ganggun,#gangknife,#blood,#hr').hide(-100);
    var hr=$('#hr');
    var main=$('#main');
    var batman=$('#batman');
    var car=$('#car');
    var hobo=$('#hobo');
    var cop=$('#cop');
    var knife=$('#knife');
    var gangfight=$('#gangfight');
    var ganggun=$('#ganggun');
    var gangknife=$('#gangknife');
    var blood=$('#blood');
    var text=$('#text');
    var button=$('#button');
    $('#start').html('Are you ready to play?');
    $('#button').html('<button id="yes">Yes</button><button id="no">No</button>');
        $('#yes').click(function(){
            $('#yes,#no').hide(function(){
                $('#start').hide();
                main.fadeIn(-100);
                hr.fadeIn(-100,function(){
                text.delay(1000).html("You were just wandering around in the streets of new york, when suddenly.. You see batman!! You've never really liked him, what do you do?")
                    button.html('<button id="fight">Fight</button><button id="leave">Leave</button>',function(){
                        batman.fadeIn(1000);
                        $('fight').click(function(){
                        });
                        $('leave').click(function(){
                            text.fadeOut(function(){
                                text.text('Good call. As you leave, you encounter a hobo. What do you do?');
                            });
                        });
                    });
                });
            });
        });
        $('#no').click(function(){
            $('#yes,#no').hide();
            $('#start').text('Oh, okay then. Come back later!');
        });
    });

I'm just wondering.. How can I set callback functions to the 'fight' and 'leave'.
If you're wondering why there's all these variables at the start, those are just the images and characters.

4条回答
Rolldiameter
2楼-- · 2019-01-05 06:34

$('fight') selects fight tag, not the tag with fight id. Try to use $('#fight') instead.

查看更多
Root(大扎)
3楼-- · 2019-01-05 06:42

You can't set a click handler on an element that doesn't exist. What you should do is use .on to bind a element further up the tree. Something like:

$("#someparentelement").on("click", "#yes", function() {
    // your code
});
查看更多
Rolldiameter
4楼-- · 2019-01-05 06:49

Don't use the click(), use on('click') and attach it to the document.

Creating a handler this way, will ensure that any new elements will be able to trigger the event.

查看更多
Explosion°爆炸
5楼-- · 2019-01-05 06:53

Which version of jQuery are you using? You should probably use jQuery.on() in this situation since your click handler code probably gets executed before the button is actually available in the DOM.

$("#button").on("click", "#yes", function (event) {
    // Your yes-button logic comes here.
});

For more details and possibilities, read about the .on(events [, selector ] [, data ], handler(eventObject)) method in the jQuery documentation:

If selector is omitted or is null, the event handler is referred to as direct or directly-bound. The handler is called every time an event occurs on the selected elements, whether it occurs directly on the element or bubbles from a descendant (inner) element.

When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.

In this case, you want to delegate the event since your element is not yet available in the DOM when you're binding the event.

查看更多
登录 后发表回答