在函数之外询问变量

时间:2013-07-18 17:53:33

标签: jquery

我是jQuery的新手,想知道如何在此函数外部访问$ hidden: $(this).hide(500,function()

HTML

<div class="fl person"> 
    <input type="hidden" name="userSaved" value="1" /> 
    <img src="..." class="circle-mask" /> 
</div>

<div class="fl person"> 
    <input type="hidden" name="userSaved" value="2" /> 
    <img src="..." class="circle-mask" /> 
</div>

的jQuery

<script>
$("div.person img").click(function () {    
    $(this).hide(500, function () {
        $(this).parent("div").empty();
        $(".main_page").appendTo("div.main_page").addClass("fl person"); 
        var saved_id_user_who_voted = $hidden = $(this).siblings('input');
    });

    /* attach a submit handler to the form */
    var saved_id_user_who_voted_val = "<?php echo $_SESSION['id']; ?>";

    /* stop form from submitting normally */
    event.preventDefault();

    /* Send the data using post and put the results in a div */
    $.ajax({
        url: "saveSavedUserToDatabase.php",
        type: "post",
        data: {saved_id_user_who_voted:saved_id_user_who_voted_val, saved_id_user_voted_on:saved_id_user_voted_on_val} 
    });
});
</script>

我希望能够访问当前函数之外的 saved_id_user_who_voted ,以便我可以使用.ajax发布它 - 现在它不在范围内。

感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

hide回调中执行您的AJAX请求。或者在hide回调之外声明变量。

$("div.person img").click(function () {
    $(this).hide(500, function () {
        $(this).parent("div").empty();
        $(".main_page").appendTo("div.main_page").addClass("fl person");
        var saved_id_user_who_voted = $hidden = $(this).siblings('input');

        /* attach a submit handler to the form */
        var saved_id_user_who_voted_val = "<?php echo $_SESSION['id']; ?>";

        /* stop form from submitting normally */
        event.preventDefault();

        /* Send the data using post and put the results in a div */
        $.ajax({
            url: "saveSavedUserToDatabase.php",
            type: "post",
            data: {
                saved_id_user_who_voted: saved_id_user_who_voted_val,
                saved_id_user_voted_on: saved_id_user_voted_on_val
            }
        });
    });
});