开发者

Switching function states

I would like to implement a API of Javascript that sort of resemble a light switch.

For instance, there are two buttons on the actual HTML page act as the UI.

Both of the buttons have event handlers that invokes a different function.

Each function have codes that act like a state, for instance.

button1.onclick=function (){
   $("div").click(
        //code effects 2
   )
}

button2.onclick=function (){
   $("div").click(
        //Code effects 2
   )
}

I the code works fine on the surface but the 2 state functions overlap.

the effects is going to take place for the rest of the way until the next reload of the document.

Basically what I want to achieve is that when 1 button is clicked, it will switch "OFF" the state of function invoked by the other button and vice versa.

Thus, the effects achiev开发者_运维问答ed are unique are not overlapped.

Is there anyway to achieve this or could any experts point me to the right direction.

Thanks in advance.


To do this you simply need a place to store the 'state'. You could simply store the on/off information in a cookie. Each javascript function could then check and/or update the value in the cookie.

On page load you could set the initial state in the cookie to whatever you want (on/off)

Using jQuery, sample:

$(document).ready(function(){

    //set cookie to OFF state during initial load

    //add event handler for On button
    $('#buttonOn').click(function(){
        //set cookie to ON
    });

    //add event handler for Off button
    $('#buttonOff').click(function(){
        //set cookie to OFF
    });

});

jQuery has many plugins for cookie support. Best one I've used is: http://www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜