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

查看:23
本文介绍了如何在模态窗口中执行 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天全站免登陆