正在跳过e.preventDefault();有条件的

时间:2014-05-18 10:54:32

标签: javascript jquery

我有以下html:

     <ul id="menu" class="clearfix">
                <li class="login-link">
                    <a href="/Account/Login">LOGIN AREA</a>

                </li>

                <li class="cart">
                    <span id="spCartCount">
                        1
                    </span>
                    <a href="#">
                        <img src="/images/cart.png"></a>           
                </li>
                <li class="login-link">

                      <a href="/Account/LogOff">Log Out</a>
                </li>
        </ul>

和Js代码:

 $("#menu li:not(.cart) a").on("click", function (e) {

        e.preventDefault();

        $("#menu li.cart > a").next(".popover").hide();
        $(this).next(".popover").fadeToggle();
    });

当用户单击“注销”按钮时,由于e.preventDefault(),它们不会重定向到注销页面;我想跳过e.preventDefault();如果用户单击“注销”

我试过了:

 $("#menu li:not(.cart) a").on("click", function (e) {

          if ($("#menu li:not(.cart) a:contains('LogOff')")) {

        } else {
            e.preventDefault();
        }

            $("#menu li.cart > a").next(".popover").hide();
            $(this).next(".popover").fadeToggle();
        });

但它没有用 怎么做?

2 个答案:

答案 0 :(得分:0)

您需要检查当前点击的元素:

$("#menu li:not(.cart) a").bind("click", function (e) {
    if ($(this).attr("href").indexOf("LogOff") < 0)
        e.preventDefault();

    $("#menu li.cart > a").next(".popover").hide();
    $(this).next(".popover").fadeToggle();
});

答案 1 :(得分:0)

在事件触发器上,首先需要识别元素,然后在href / class等中检查所需的值。

&#39;这&#39;关键字可用于获取当前元素

$("#menu li:not(.cart) a").bind("click", function (e) {
    if ($(this).attr('href').indexOf('LogOff') != -1)
        e.preventDefault();

    $("#menu li.cart > a").next(".popover").hide();
    $(this).next(".popover").fadeToggle();
});

&#39; e.target&#39;可以使用。

$("#menu li:not(.cart) a").bind("click", function (e) {
    if ($(e.target).attr('href').indexOf('LogOff') != -1)
        e.preventDefault();

    $("#menu li.cart > a").next(".popover").hide();
    $(this).next(".popover").fadeToggle();
});