How to execute jquery inside a Modal window?

2019-01-29 01:49发布

问题:

I need to fire some actions when the state of a textfield is focused.

This code works (tested) fine if the textfield its a standard inline element. But it does not work if the textfield is inside a Modal window. I guess that the modal window is hidden at the moment the jquery library is loaded and then the problem.

How can I get this working?

    $('#name').focus(function() {
console.log('do something');
}); 

回答1:

I guess that the modal window is hidden at the moment the jQuery library is loaded and then the problem.

you guessed correctly, probably you load the content of your modal dialog after a certain event.

Now the code:

$('#name').focus(function() {
console.log('do something');
}); 

is probably attached to the $(document).ready() event which fires on each loading of a new document but dose not fire when an ajax call is completed

To overcome this problem you need to attach a delegate for the loading event of the dialog that will run your required function. See on API or LIVE depending on your jQuery Version http://api.jquery.com/on/

If you want you can just use a generic delegate for each click event that is made and try to attach your focus event after each click is made like this:

$(document).on("click", "#name", function() {
    $(this).focus(function() {
        console.log('do something');
    });
});

This will try to attach the focus function to the #name element after each click is made, that is if the #name element exists.