2

我是 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 发布它 - 现在它不在范围内。

任何帮助表示赞赏。

4

1 回答 1

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
            }
        });
    });
});
于 2013-07-18T18:23:19.020 回答