首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JS全局变量不更新

JS全局变量不更新
EN

WordPress Development用户
提问于 2020-03-12 10:04:15
回答 2查看 798关注 0票数 0

如何更新全局变量URL?在过去的三天里,我一直在努力,仍然没有运气。

代码语言:javascript
复制
var output = '';
var pageNum = '';
url = '';
function post_ajax_get(pagination) {
    $("#loading-animation").show();
    var query = 'nazwa=';
    var time = 'gr=';
    var output = '';
    $("[data-category-menu] a.current").each(function(){
        if($(this).data('time')) {
            if(time != 'gr=') {
                time+= ','; 
            };
            time+= $(this).data('time');
        }
        if($(this).data('slug')) {
            if(query != 'nazwa=') {
                query+= ','; 
            };
            query+= $(this).data('slug');
        }
        if (query != 'nazwa=' && time == 'gr='){
            output = query;
        }
        else if (query == 'nazwa=' && time != 'gr='){
            output = time;
        }
        else if (query != 'nazwa=' && time != 'gr='){
            output = time + '&' + query;
        }
    });
    if(pagination) {
        $("[data-pagination] a.current").each(function(){
            if(output != '') output+= '&';
            output+= $(this).data('slug');
        });
    }
    url = window.location.protocol + '//' + window.location.host + '/' + window.location.pathname + '?' + output;
    //window.location.href = url;
    if ($('body.category').length > 0 && output == '') {
        var adres = window.location.pathname;
        var cat = adres.split('/')[3];
        url = window.location.protocol + '//' + window.location.host + '/' + window.location.pathname + '?' + 'nazwa=' + cat;
        $('[data-category-menu] li a').each(function() {
            if($(this).attr('id') == cat) {
                $(this).addClass('current');
            }

            $('[data-category-menu] li a.current').click(function() {
                $(this).removeClass('current');
            }) 
        })
    }

    $('[data-category-menu] li a.current').click(function() {
        updateURL(); 
    })

    function updateURL() {
        console.log('fire');
        url = window.location.protocol + '//' + window.location.host + '/' + window.location.pathname + '?' + 'nazwa=pusty';
    }
    console.log(url);
    var pageNum = url.substr(url.indexOf("md_page=") + 8);
    //var pagNum = pageNum.toString();
    $('#md-products').load(url + ' #md-products > *', function() {
        $("#loading-animation").hide();
        $('#md-products [data-pagination] a').on('click', function() {
            $(this).addClass('current');
            post_ajax_get(true);
        })
    });
}

console.log(url);
EN

回答 2

WordPress Development用户

发布于 2020-03-12 10:19:56

如果要有意创建全局变量,则需要这样做。

window['your_variable_name']= 'Some variable value'

然后,您就可以像window.your_variable_name一样访问它了--这种创建和访问全局变量的方式保证了您将使用相同的变量,而不管webpack这样的构建工具是什么,也不管您从哪里访问它。例如,您可能需要从其他函数访问它,而其他函数又定义了相同的命名变量,因此,如果不通过window.variable_name符号引用变量,您将访问父作用域的变量,而不是全局变量。

另外,如果您需要一个全局变量,那么它的名称应该是唯一的,而且很好的做法是像您的插件名那样称呼它或者其他代码不会覆盖的东西,避免使用像url这样的通用名称。

所以你可以这样做,window['YourUniquePluginGlobal'] = {url: 'your_url'};

然后您将能够访问您的变量,如window.YourUniquePluginGlobal.url

不要依赖省略var关键字。

更重要的是,在声明变量时,不要忽略var (或let,ES6中的const ),因为它会使您的代码变得不可靠和不可维护。

在声明JS中的变量时,始终使用varlet \ const,并希望好的代码与您一起使用:)

票数 0
EN

WordPress Development用户

发布于 2020-03-12 11:32:50

我不知道用于生成所使用的标记的全部代码,但总的来说,在基于代码的基础上思考之后,我看到了,甚至看不到其余的代码。我希望重写的代码可以让您深入了解如何在没有全局变量的情况下实现您想要完成的任务。

代码语言:javascript
复制
//lets init UI
$('#md-products [data-pagination] a').on('click', function () {
    $(this).addClass('current');
    var pageToLoad = $(this).attr('data-page'); // set to attribute which contains page to load.
    var url2Load = getUpdatedUrl(pageToLoad);
    post_ajax_get(url2Load);
});

$('[data-category-menu] li a').each(function () {
    var cat = getCurrentCategoryFromPathName();
    if ($(this).attr('id') === cat) {
        $(this).addClass('current');
    }
});

$('[data-category-menu] li a.current').on('click', function () {
    $(this).removeClass('current');
    updateURL();
});


/**
 * Function where you perform something - for example loading of new category's items. see above.
 */
function updateURL() {
    console.log('fire');
    // url = window.location.protocol + '//' + window.location.host + '/' + window.location.pathname + '?' + 'nazwa=pusty';
    var updatedUrl = getUpdatedUrl(0); // i guess by default you want to display first page when changing a category.
    // do something with this ulr.
    console.log(updatedUrl);
    // so really you can do to load new items.
    post_ajax_get(updatedUrl);
}


/**
 *  Really simplified just loads whetever you pass in.
 * @param  URL url_to_load
 */
function post_ajax_get(url_to_load) {

    $("#loading-animation").show();

    $('#md-products').load(url_to_load, function () {
        $("#loading-animation").hide();
    });
}


/**
 * It returns a URL bases on current category and UI states as well as receives pageNumber to load if it's paginated
 * 
 * @param pageNumber
 * @returns {string}  Url which you can load or work with.
 */
function getUpdatedUrl(pageNumber){
    var newUrl =  window.location.protocol + '//' + window.location.host + '/' + window.location.pathname;
    var query = 'nazwa=';
    var time = 'gr=';
    var output = '';

    $("[data-category-menu] a.current").each(function () {
        if ($(this).data('time')) {
            if (time != 'gr=') {
                time += ',';
            };
            time += $(this).data('time');
        }
        if ($(this).data('slug')) {
            if (query != 'nazwa=') {
                query += ',';
            };
            query += $(this).data('slug');
        }
        if (query != 'nazwa=' && time == 'gr=') {
            output = query;
        } else if (query == 'nazwa=' && time != 'gr=') {
            output = time;
        } else if (query != 'nazwa=' && time != 'gr=') {
            output = time + '&' + query;
        }
    });

    newUrl = newUrl + '?' + output;

    if ($('body.category').length > 0 && output === '') {
        var cat = getCurrentCategoryFromPathName();
        newUrl = window.location.protocol + '//' + window.location.host + '/' + window.location.pathname + '?' + 'nazwa=' + cat;
    }

    if(pageNumber){
        newUrl = newUrl + '&md_page=' + pageNumber;
    }

    return newUrl;
}

/**
 * Just extracted logic of getting category from path.
 * @returns string
 */
function getCurrentCategoryFromPathName(){
    return  window.location.pathname.split('/')[3];
}

再说一次,这只是基于对代码的理解而对代码的盲目假设。所以这不是一个复制粘贴的解决方案,但我希望它能帮助你找到好的解决方案。

票数 0
EN
页面原文内容由WordPress Development提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://wordpress.stackexchange.com/questions/360535

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档