从不同范围访问较新版本的变量(JavaScript / jQuery)

时间:2015-12-07 01:05:35

标签: javascript jquery html scope

当单击后退按钮时,我想用已加载的变量data1填充结果div。使用此代码,单击后退按钮时,结果div将设置为""。如何访问较新版本的data1?

Javascript:

function finddata(def,id){
    $("#doctitle").html($("#exp").val() + " - Writer's Dictionary");
    $("#results").html('<span class="glyphicon glyphicon-cog glyphicon-spin" title="loading..."></span>').fadeIn();
    if (def == 1) {
        var word = id.innerHTML;
        $.get( "processor.php?query=" + word + "&def=" + def, function(data2) {
            $("#results").html(data2);
            $("#back").click(function(){
                $("#results").html(data1);
            });
        });
    } else {
        $.get( "processor.php?query=" + $("#exp").val(), function(data1) {
            $("#results").html(data1);
        });
    }
}

HTML:

<div class="container">
    <div class="col-md-6 col-md-offset-3" id="results">
    <div id="back">Back</div>
    </div>
</div>

1 个答案:

答案 0 :(得分:1)

尝试

<div id="back" onclick="finddata(2)">Back</div> 

def参数设置为1以外的值,该$.get()应在else <{1}} finddata语句中调用var data; function finddata(def) { if (def === 1) { // do stuff } else { // if `data` defined if (data) { // do not do stuff here } // else call `.get()` else { var word = id.innerHTML; $.get( "processor.php?query=" + word + "&def=" + def, function(data2) { $("#results").html(data2); $("#back").click(function(){ $("#results").html(data1); }); }); } } } $("#back").click(function() { finddata(2) })

修改,更新

public class SearchCredential
{
    public string Employee { get; set; }
    public string CostCenter { get; set; }
}

jsfiddle http://jsfiddle.net/229ad2b2/2/