【问题标题】:Onload jQuery event to call function and make it "live"加载 jQuery 事件以调用函数并使其“活动”
【发布时间】:2013-09-09 05:08:05
【问题描述】:

在 jQuery 中存在任何附加这样一个事件的事件:

$("body").on("click", "#test", function () {
    // some code here...
});

我可以附加到loadready 事件,以替换:

$(document).ready(function () {
    // Some code...
});

我需要这个,因为我在一个外部文件中有 $(document).ready(); 范围,它进行了一些表单验证,并且在我的 HTML 中我通过 ajax 加载了一些内容,然后在该范围内的所有内容都不起作用。

换句话说,我希望$(document).ready(); 中的所有内容都留在页面上的live,使用类似.on 的内容。

如果我将 HTML 直接放在页面中,不使用 ajax,则验证有效。

知道如何解决这个问题吗?

【问题讨论】:

    标签: jquery javascript-events


    【解决方案1】:

    作为建议:

    授予对验证函数的全局访问权限,然后使用 AJAX 回调来调用此验证函数。

    【讨论】:

    • 我该怎么做?从未听说过 JavaScript 中的 global access
    • 关于变量没关系,但是我想要的函数呢?
    • @WellingtonZanelli window.my_function = function() { /* code */ };
    【解决方案2】:

    我假设在 ajax 调用之后附加了 id 为“test”的元素。 然后你可以像这样使用来使元素准备好。

    您可以在单个文件/或多个 javascript 文件中添加准备好的多个文档。 但我建议您将代码放在一个函数中,然后从外部文件的 document.ready 范围调用该函数。

    function doSomething()
    {
        $("#test").on('click', function(){
          //do some thing here
        });
    }
    

    外部文件:

     $(document).ready(function(){
    ....
    .....
    
    try{
    doSomething(); 
    }
    catch()
    {
    //this section will be hit when the method is not avavilble.
    }
    });
    

    【讨论】:

    • 是的,它在最近的几个版本中被贬低了。我误解了你的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-08
    • 1970-01-01
    • 2011-02-27
    • 1970-01-01
    • 2014-03-20
    相关资源
    最近更新 更多