【问题标题】:onclick jquery menu not working after ajaxajax后onclick jquery菜单不起作用
【发布时间】:2012-05-29 20:30:48
【问题描述】:

遇到一些 jquery 和 ajax 的问题。基本上用户通过ajax形式登录。该表单位于 jquery onclick 下拉菜单中,该下拉菜单也用于购物车菜单(只是更改了命名代码(css + jquery),因此不会相互冲突,并且两者都可以正常工作,直到用户登录(通过 ajax))。

下面是jquery代码

//////Cart App
jQuery(".dropdown-cart dt a").click(function() {
        // Change the behaviour of onclick states for links within the menu.
    var toggleId = "#" + this.id.replace(/^link/,"ul");

        // Hides all other menus depending on JQuery id assigned to them
    jQuery(".dropdown-cart dd ul").not(toggleId).hide();

        //Only toggles the menu we want since the menu could be showing and we want to hide it.
    jQuery(toggleId).toggle();

        //Change the css class on the menu header to show the selected class.
    if(jQuery(toggleId).css("display") == "none"){
        jQuery(this).removeClass("selected");
    }else{
        jQuery(this).addClass("selected");
    }
});

jQuery(".dropdown-cart dd ul li a").click(function() {

    // This is the default behaviour for all links within the menus
    var text = jQuery(this).html();
    jQuery(".dropdown-cart dt a span").html(text);
    jQuery(".dropdown-cart dd ul").hide();

});

jQuery(document).bind('click', function(e) {

    // Lets hide the menu when the page is clicked anywhere but the menu.
    var $clicked = jQuery(e.target);
    if (! $clicked.parents().hasClass("dropdown-cart")){
        jQuery(".dropdown-cart dd ul").hide();
            jQuery(".dropdown-cart dt a").removeClass("selected");
        }

});

我已经尝试了一些 .live 组合,甚至是 .delgate,但在用户登录后,登录和购物车 onclick 菜单仍然无法工作,直到页面刷新

有什么想法吗??

干杯 nz战士

【问题讨论】:

  • 你有什么 jquery 版本?
  • 你的代码准备好了吗??
  • 在您向我们展示您的 ajax 代码之前,我们只是在猜测。

标签: jquery css ajax


【解决方案1】:

我猜你是在用户通过 ajax 登录后更新锚标签。所以你之前注册的事件绑定(点击事件)会丢失。您应该使用 jQuery on 进行绑定而不是单击

这段代码

jQuery(".dropdown-cart dt a").click(function() {
     //remaining code   
});

应该改为

$(document).on("click",".dropdown-cart dt a",function() {
    //remaining code   
});

jquery on 适用于当前元素和未来元素,可用于 jQuery 1.7+ 版本。

【讨论】:

  • 你救了我的命 :p @Shyju
【解决方案2】:

试试这个

将代码包装到function 中并使用onclick 事件在您的html 标记中调用该函数

onclick='function_name(this)' --> in your html tag

function function_name(element){
   //your code here
}

【讨论】:

    【解决方案3】:

    替换:

    $(".dropdown-cart dt a").click(function(){})
    

    与:

    jQuery 1.7+

    $(".dropdown-cart").on("click","dt a", function(){})
    

    jQuery 1.4.3+

    $(".dropdown-cart").delegate("dt a", "click", function(){})
    

    jQuery 1.3+

    $(".dropdown-cart dt a").live("click",function(){})
    

    在这种情况下,您不需要绑定新的 ajax 加载组件。

    【讨论】:

    • .delegate 的使用更适合 1.7 或 1.6 之前的 jquery 版本
    • 是的。 delegate 更接近 .on 方法,同意,应该比 .live 执行得更快 ...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-13
    • 2020-01-26
    • 1970-01-01
    相关资源
    最近更新 更多