开发者

jquery event preventDefault in a function

This is my first code:

$j('.toggle').delegate('','click',function(e){
    e.preventDefault();
});

This is stopping my a-tag from doing anything.

Now I want this in a function like this:

$j('.toggle').delegate('','click',function(e){
    banner();
});

if(x)
{
banner();
}

function banner() 
{ 
e.preventDefault(); 
}

But I can't use the event now, how can I solve this?

EDIT

Thanks for the response, but I solved my problem another way. This is the code if you are interested. When you hide a banner, the banner will stay hidden on all pages, checking a cookie. When you open it again, it will stay open on all pages.

    // Set cookie if there is no cookie
    if(getCookie() != 0 && getCookie() != 1)
    {
        setCookie(1);
    }

    // Close the banner if cookie = 0 when page loads
    if(getCookie() == '0')
    {
        closeBanner();
    }

    // Set the cookie   
    function setCookie(status) {
        $j.cookie('status', status, { path: '/', expires: 100 });
        return false;
    }

    // Get the cookie
    function getCookie() {
        //console.log($j.cookie('status'));
        return $j.cookie('status');
    }

    // Close and open the banner on click

    $j('.toggle').delegate('','click',function(e){
        e.preventDefault();

        if(getCookie() == 1)
        {
            setCookie(0);
            closeBanner();
        } else if(getCookie() == 0)
        {
      开发者_Go百科      setCookie(1);
            openBanner();
        }
    });

    // Close the banner
    function closeBanner()
    {
        var src = $j('#img_lipke').attr("src").replace("lipske", "lipske_down");
        $j('#img_lipke').attr("src", src);
        $j('#bannerbottom').css('margin-top','5px');

        changeBanner();
    }

    // Open the banner
    function openBanner()
    {
        var src = $j('#img_lipke').attr("src").replace("lipske_down", "lipske");
        $j('#img_lipke').attr("src", src);
        $j('#bannerbottom').css('margin-top','0');

        changeBanner();
    }

    // Open or close the banner
    function changeBanner(e) 
    {
        $j('#banner').animate({ 
            height: 'toggle'
        }, 800, function() {
            // Animation complete.
        });
    }


Just add the preventDefault after your call to banner

$j('.toggle').delegate('','click',function(e){
    banner();
    e.preventDefault();
});


I'm not sure what you're trying to accomplish, but if you want to use the event object in the banner function, just pass it.

$j('.toggle').delegate('','click',function(e){
    banner(e); // pass "e" as argument
});

function banner(e) {
    e.preventDefault();
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜