如何存储和重现jQuery事件

时间:2013-01-01 16:44:34

标签: javascript json jquery

我正在尝试将jQuery事件存储在DB中。

//Calling this Function On Click 

function trackevent(event){
    window.events.push(event)
}

$.each(window.events, function(i, item){
    console.log(i +" - "+ $.parseJSON(item));
});

事件已存储到数组中。这很酷,但如果我试图遍历window.events,我就无法获得jQuery事件JSON。我无法弄清楚我的错误。任何建议都会有所帮助。

enter image description here

如果我将parseJSON更改为JSON.stringify

,我收到此错误
$.each(window.events, function(i, item){
    console.log(i +" - "+ JSON.stringify(item));
});

enter image description here

enter image description here

$(document).ready(function(){
window.events = []
// Function to enable the hidden checkbox button
$(".answers_checkbox").click(function(){
    current_click = $(this).attr("data-attr");

    // If the Hidden checkbox is Checked , it means its already selected (blue)
    if($("."+this.id).attr('checked') == 'checked') {
        $(this).css('background-image', '');
    } else {
        // Changing the Background Image to current_click option
        $(this).css('background-image',"url('/assets/choice_buttons/choice"+current_click+"_Sq_Blue.png')");
    }

    $("."+this.id).attr('checked',!$("."+this.id).attr('checked'));
    trackevent(event);
});

function trackevent(event){
    window.events.push(event)
}

});

// Function to Save Events
$(window).bind('beforeunload', function(){
    $.each(window.events, function(i, item){
        console.log(i +" - "+ item);
    });
});

1 个答案:

答案 0 :(得分:2)

parseJSON解析JSON的字符串并返回一个对象。你不应该把它作为一个对象。

由于您无论如何都要登录到控制台,您也可以记录整个对象而不是字符串表示:

console.log(i, item);

以下是演示:http://jsfiddle.net/HjcGT/1/