jQuery UI:通过AJAX加载内容后重新初始化函数 [英] jQuery UI: Re-initializing a function after loading content via AJAX

查看:100
本文介绍了jQuery UI:通过AJAX加载内容后重新初始化函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我几天来一直在寻找这个问题的答案,虽然我已经找到了问题的大部分答案,但我的代码仍然有一段不像之前那样有效添加AJAX调用。

I've been searching all over for an answer to this question for a few days now, and while I have found most of the answer to my problem, there's still one piece of my code that is not working as it did before adding AJAX calls.

一些背景:我正在创建一个Web应用程序作为RPG角色生成器。首先发生的事情之一是我创建jQuery UI微调器小部件来调整统计分数。在停止事件中,我的代码运行一个函数,根据switch案例检查当前数字,以设置一个值,从初始池中添加或减去多少个点(Point-Buy系统,对于任何了解这些事情的人):

Some background: I am creating a web app to serve as an RPG character generator. One of the first things that happens is I create jQuery UI spinner widgets to adjust stat scores. On the stop event, my code runs a function that checks the current number against a switch case to set a value to how many points are added or subtracted from an initial pool (Point-Buy system, for anyone who knows about these things):

function calcPtsLeft() {

        var ptssum = new Number();
        var ptsmax = new Number($("#maxpoints").val());

        var pbstr = pointBuy($strsc.val());
        var pbdex = pointBuy($dexsc.val());
        var pbcon = pointBuy($consc.val());
        var pbint = pointBuy($intsc.val());
        var pbwis = pointBuy($wissc.val());
        var pbcha = pointBuy($chasc.val());

        var ptssum = pbstr + pbdex + pbcon + pbint + pbwis + pbcha;

        ptsleft = ptsmax - ptssum;

        $("#ptsleft").val(ptsleft);
    };

    calcPtsLeft();

此代码运行正常,直到我决定使用AJAX调用动态加载各种页面为#内容div。在进行AJAX调用以加载我的角色生成器之后,我的小部件根本没有显示出来。我发现这是由于委托问题,所以我将我的所有小部件初始化收集到一个函数中:

This code functioned properly, up until I decided to use AJAX calls to dynamically load various pages into a #content div. After making the AJAX call to load my character generator, my widgets didn't show up at all. I found that this was due to a delegation problem, so I collected all of my widget initialization into a function:

function initGenWidgets() {

//sets CSS for input/label items from jQuery UI set 
$("#slider input:text, #slider label, #remaining input:text, #remaining label, #charName, #charAge")
    .addClass("ui-spinner ui-spinner-input");   

//initialize jQuery UI button widget
$("button").button();

//initialize jQuery UI radio buttonset widget
$("#genderbuttons").buttonset();

//initialize jQuery UI menu widget
$("#raceradio").menu();

//initialize jQuery UI vertical tabs
$("#char-gen").tabs().addClass("ui-tabs-vertical ui-helper-clearfix");

$("#char-gen li").removeClass("ui-corner-top").addClass("ui-corner-left");

//initialize jQuery UI spinner widget for age
$("#charAge").spinner({
    icons: {
        down: "ui-icon-minus",
        up: "ui-icon-plus"
    }
});

//initialize jQuery UI spinner widget for stats
$(".statspinner").spinner({
        min : 7,
        max : 18,
        icons : {
            down : "ui-icon-minus",
            up : "ui-icon-plus"
        },
        stop: function(event, ui) {
            calcPtsLeft();
        }
    });

//initialize jQuery UI slider widget for point-buy allotment
$("#pointslider").slider({
        value: 20,
        min: 15,
        max: 40,
        step: 5,
        slide: function(event, ui) {
            $("#maxpoints").val(ui.value);
            calcPtsLeft();
        }
    });
};

我现在按如下方式进行AJAX调用:

I now make the AJAX call as follows:

//function to load php files into content div
function loadContent($page){
    $("#content").load($page+' > *', function(response, status){
            success: initGenWidgets();
    });
};

//nav links load files into content div
$(".menulink").on("click", function(e){
    e.preventDefault();
    loadContent($(this).attr("href"));
});

一切似乎都很好,但是当我测试小部件时,似乎我的微调器不再执行停止时的 calcPtsLeft()函数。滑块用于在我滑动后更新#ptsLeft值(稍后修复),但是微调器根本不更新值。

Everything seems to load fine, but when I test the widgets, it seems that my spinners no longer execute the calcPtsLeft() function on stop. The slider works to update the #ptsLeft value after I slide it (going to fix that later), but the spinners do not update the value at all.

我是什么在这里做错了,或者根本不做这里?任何帮助将不胜感激。

What am I doing wrong here, or not doing at all here? Any help would be greatly appreciated.

推荐答案

jQuery .load()



脚本执行


使用不带后缀的URL调用 .load()时selector
表达式,在删除
的脚本之前,将内容传递给。 html()。这将在丢弃之前执行脚本块。如果调用
.load()并在页面附加一个选择器表达式,
但是,在更新DOM之前会删除脚本,
因此不执行。两种情况的示例可以在下面看到

When calling .load() using a URL without a suffixed selector expression, the content is passed to .html() prior to scripts being removed. This executes the script blocks before they are discarded. If .load() is called with a selector expression appended to the URL, however, the scripts are stripped out prior to the DOM being updated, and thus are not executed. An example of both cases can be seen below

.load的文档的一小部分但重要的部分( )!如果你真的想执行它们,你可能需要做某种 eval(),或者丢弃 .selector

A small but important segment of the docs for .load()! If you really wanted to execute them, you'll probably have to do some sort of eval(), or discard the .selector

此处,任何加载到中的JavaScript #a 作为文档的一部分将成功执行。

Here, any JavaScript loaded into #a as a part of the document will successfully execute.

$( "#a" ).load( "article.html" );

但是,在下列情况下,文档中的脚本块被加载到 #b 被剥离且执行:

However, in the following case, script blocks in the document being loaded into #b are stripped out and not executed:

$( "#b" ).load( "article.html #target" );



可能的解决方案



嗯,经过测试 - 我决定实际上采取将功能添加到窗口的步骤,因为它是跨越功能的最佳方式。通过许多脚本的方法。这个,希望修复有未声明的函数被声明,因为你在一个不同的脚本&命名空间。

Possible Solution

Well, after testing - I decided to actually take the step of adding the functions to the window, simply because it's the best way of carrying across functions & methods via many scripts. This, hopefully fixes have undefined functions being declared, because you're in a different script & namespace.

Main.php

<script>

    //Create Rgp Object
    var Rgp = {
       calcPtsLeft : function() {
            console.log( 'Calculate Points' );
       },
       addPoints : function() {
            //Some addPoints Function
       }
    }; 

    //Add Object to Window      
    window.Rgp = Rgp;

    $('#begin').on('click', function() {
        $("#content").load( 'someScript.js', function( response, status ){
            success: initGenWidgets();
        });
    });

</script>

someScript.js

<script>
function initGenWidgets() {
   $("#pointslider").slider({
       value: 20,
       min: 15,
       max: 40,
       step: 5,
       slide: function(event, ui) {
            $("#maxpoints").val(ui.value);
            Rgp.calcPtsLeft(); //Prints 'Calculate Points'
       }
   });
}
</script>

这篇关于jQuery UI:通过AJAX加载内容后重新初始化函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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