首页 > 解决方案 > 返回数据在特定的 if 语句中不起作用

问题描述

我正在使用我在下面生成的这个 javascript 翻译网页,我在转换输入中的文本时遇到问题,所以我尝试将 if 条件放在我的代码中,如果它是输入,则使用返回,如果不使用 .html,但我有问题退货是因为它不起作用而且我不知道为什么(请参阅代码中的注释以提供更多信息)

function changeLanguage(lang){
$.post("/misc/sessionUpdate.asp",{ 'lang': lang}); 
$.getJSON("/language/"+lang+".json", function( data ) {

    $.each(data, function(property, val){

        $('[data-localize]').val(function() {
            type =  $(this).attr("type");
            attrVal = $(this).attr("data-localize");
                    // if put return data[property]; here it is working but the problem it should be inside the if(attrVal == property)
            if(attrVal == property){
                if (type == "submit"){
                    // i already tried console.log (attrVal +"=="+ property) to verify if there is an instance of true and there is
                    return data[property];
                }else{
                    attrName = '[data-localize="'+property+'"]'; //sample format [data-localize=menu]
                    $(attrName).html(val); // data[property] is the corresponding value of the key in json
                }
            }               
        });
    });
}).done(function(){
    $('.languageLoader').css('display','none');
});
}

我还将算法放在 .done 函数中,以避免 ajax 中的异步问题,但仍然无法正常工作

提前谢谢各位....

标签: javascriptjquery

解决方案


如下所示更新您的循环。

$.each(data, function(property, val){
    $('[data-localize="' + property + '"]').each(function(index, item) {
        type =  $(this).attr("type");   
        if (type == "submit") {
            $(this).val(data[property]);
        } else {
            $(this).html(val);
        }
    });
});

推荐阅读