点击<a> element not removed when using .off()

时间:2016-04-26 22:08:15

标签: jquery click

I'm trying to remove a click handler from an a element, but .off() does not remove it. I already looked herehere上的处理程序。

我的HTML(在document.ready()事件中动态生成):

<ul id="catalog">
<li data-id="2">
    <div class="item">
        <div class="image">
            <a href=""><center><i class="fa fa-picture-o fa-lg noitemimage"></i></center><span class="txt">My title</span></a>
        </div>
        <div class="details"><button class="delete btn-primary-grey-s">Delete</button></div>
    </div>
</li>
</ul>

使用Javascript:

$(document).on('click', '#catalog a', function () {
    ShowData();
    return false;
});

在用户操作中,调用以下代码,我想删除在上面的代码中设置的单击处理程序。但是,执行后我仍然可以单击超链接,上面的代码仍然执行。

$.ajax({
    type: "GET",
    url: "/api/deleteitem/?itemid=" + itemid,
    data: "",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {

        //disable the events on this elements' "a" click

        //ALL THESE 3 OPTIONS BELOW DO NOT WORK
        //$(document).off('click', 'ul#catalog li[data-id=' + itemid + '] a', '**');
        //$('ul#catalog li[data-id=' + itemid + '] a').off();
        $('ul#catalog li[data-id=' + itemid + '] a').off('click');

    }
});

**更新1 **

        $.ajax({
            type: "GET",
            url: "/api/getitems/?id=" + id ,
            data: "",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {

                DYNAMIC HTML CODE GENERATED FROM HERE WORKS DIFFERENTLY??

                }

            }
        });

2 个答案:

答案 0 :(得分:1)

您的第一个选择器使用事件委派方法,其中document对象包含已注册的事件处理程序。当发生单击时,它会过滤并将事件委托给与子选择器匹配的子项

'#catalog a'

如果要删除事件,则必须将click handler直接添加到子元素

$('#catalog a').on('click', function () {
    ShowData();
    return false;
});

(或)您可以将offselector参数一起使用,

$(document).off('click', '#catalog a')

答案 1 :(得分:0)

1       Center for Animal Control    3
2 Department of Internal Medicine    1
3          Department of Medicine    1
4           Department of Surgery    1
5        Division of Hypertension    2
6        Division of Primary Care    1

//更新 好吧,在ajax成功之后我没有找到解决开/关的问题。我也尝试$(document).on(“click.ShowData”,“#catalog a”function(){etc ...

最后这种方法适合我。

//<a href="javascript:;">

//ShowData logs only first time

var $test = $("#catalog a");

function ShowData() {
    console.log("ShowData");
}

function doNothing() {
  console.log("Off");   
  $test.off("click", ShowData);
}

$test.on("click", doNothing); 
$test.on("click", ShowData);

//For Dynamic

   $("#catalog a").on("click.doNothing", function(){
      console.log("Off");   
      $(this).off("click.ShowData");
   }); 
   $("#catalog a").on("click.ShowData", function(){
     console.log("ShowData");
     //your ajax code
   });