访问和修改函数内外的变量

Accessing and modifing a variable in and out of functions

本文关键字:变量 函数 修改 访问      更新时间:2023-09-26

你好,我试图修改变量popText,但ajax功能失败,我无法获得popText上的输出:(

我做错了什么?

function nariTooltip(){
var popTime;
var fading;
var popboxIsActive = false;
var mouseIsHoverPopbox = false;
var popText;
//Using Event Delegation to cover late AJAX inserted DOM elements
//no need to recall function after each AJAX run
//Mouseenter / Mouseout
$("body").on(
    {
        mouseenter: function(e){
                $hoverElem = $(this);
                //Define Variables
                var popDelay = 250;
                    if ($hoverElem.attr("popdelay")){
                        var popDelay = $hoverElem.attr("popdelay");
                    }
                popTime = setTimeout(function() {
                    popText = $hoverElem.attr("poptext");
                        if ($hoverElem.next().hasClass("poptext")) {
                            popText = $hoverElem.next(".poptext").html();
                        }
                    var popAjax = $hoverElem.attr("popajax");
                    if (popAjax){
                        var popAjax = popAjax.split(':');
                        popAjaxType = popAjax[0];
                        if (popAjaxType == 'general')
                            {
                            popAjaxUrl = 'tooltip_gen.php';
                            }
                        else if (popAjaxType == 'item')
                            {
                            popAjaxUrl = 'tooltip_items.php';
                            }

                        if (popAjaxUrl){
                            $.ajax({ url: 'ajax/'+popAjaxUrl,
                            data: {id: popAjax[1]},
                            type: 'get',
                            success: function(output) 
                                {
                                popText = output;
                                },
                            error:function (xhr, ajaxOptions, thrownError){
                                 popText =  html(xhr.statusText);
                                 },
                            });
                            }

                    //alert(outputs);
                    }
                    //Create Popup
                    $hoverElem.append('<div class="popbox">' + popText + '</div>');

popText总是以popText = $hoverElem.next(".poptext").html();上赋值结束

似乎是在ajax返回之前用文本创建了div。创建一个设置popText的函数,当你从ajax获得它时调用它

function setPopText( elem, txt ) {
    $(elem).append('<div class="popbox">' + txt + '</div>')
}

在ajax

success: function ( output ) {
    setPopText( $hoverElem, output );
}