How to execute jquery inside a Modal window?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-03 18:14:43

问题


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.



来源:https://stackoverflow.com/questions/15083511/how-to-execute-jquery-inside-a-modal-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!