如何在模态窗口内执行jQuery? [英] How to execute jquery inside a Modal window?

查看:60
本文介绍了如何在模态窗口内执行jQuery?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文本字段的状态为焦点时,我需要执行一些操作.

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

如果文本字段是标准内联元素,则此代码可以正常工作(测试). 但是,如果文本字段位于 Modal窗口之内,则无法使用.我猜想模式库窗口在加载jQuery库时就隐藏了,然后出现了问题.

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.

我该如何工作?

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

推荐答案

我猜想模态窗口在jQuery的那一刻是隐藏的 库已加载,然后出现了问题.

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.

现在输入代码:

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

可能附加到$(document).ready()事件,该事件在每次加载新文档时都会触发,但在ajax调用完成时不会触发

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

要解决此问题,您需要为将运行所需功能的对话框的加载事件附加一个委托. 根据您的jQuery版本在API或LIVE上查看 http://api.jquery.com/on/

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');
    });
});

这将尝试在每次单击后将焦点功能附加到#name元素,即#name元素是否存在.

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

这篇关于如何在模态窗口内执行jQuery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆