0

好的,对不起,如果我误解或误解了任何东西,但我对 jQuery 和 javascript 还很陌生。

我在 php 中建立了一个商店,其中一个元素是一个 jQuery 购物车,它在所有页面中都是“必需的”,因此它始终在页面上。我在页面上包含以使其工作的 jQuery 如下:

$(document).ready(function(){
    $("#cbox").hover(function(){ 

         $(this).stop(true,false)
         .animate({right:  0}, 500); },
         function(){               

            $("#cbox").stop(true,false).animate({right: -120}, 500); });
    });

基本上,购物车位于页面的右侧,悬停时会弹出/滑出。

我想在用户将项目添加到购物篮时以编程方式弹出/滑出,作为一种事件通知。理想情况下使用onclick.

我曾尝试调用各个部分,但由于它是一个文档就绪的整体功能,我正在为我onclick应该说什么而苦苦挣扎。我什至不确定它是否会起作用。

任何人都可以给我一个正确的方向吗?

4

2 回答 2

1
$(document).ready(function(){
    $("#cbox").hover(function()
    { 

         $(this).stop(true,false)
                //.animate({right:  0}, 500); },function()<-- invalid syntax: leave out parentheses and semi-colon:
                .animate({right:  0}, 500,function()
                {//no need for the selecot here
                    $(this).stop(true,false).animate({right: -120}, 500);
                });
    });
    $('.storeItems').on('click',function()
    {//best use on for AJAX content, for example
        $('#cbox').trigger('hover');/
    });
 });//you were missing this closing

There's one suggestion I'd like to make: the .on('click' handler has a jQuery selector in it. This means that you'll scan the DOM on each click event for that #cbox element. You can make your code more efficient by using a closure here:

    $('.storeItems').on('click',(function(cbox)
    {
        return function()
        {//cbox is a reference to the cart element, in memory so no need to scan the dom over and over
            cbox.trigger('hover');
        };
    }($('#cbox'))));//pass the reference here

I know, there's a lot of function's and even more parentheses and brackets. You don't have to use this approach, but just keep this in the back of your mind as you go about learning more JS: you'll start using closures sooner or later, I promise :)

于 2012-11-30T12:43:32.940 回答
0

单击另一个项目时调用悬停功能是众多解决方案之一

$(document).ready(function(){
     $("#cbox").hover(function(){ 

         $(this).stop(true,false)
         .animate({right:  0}, 500); },
          function(){               

              $("#cbox").stop(true,false).animate({right: -120}, 500); });
     });

     $('.itemClicked').click(function(e){

           $('#cbox').trigger('hover');

     });

});

于 2012-11-30T12:22:05.217 回答