使用JQuery开/关调用删除click事件不起作用?

时间:2014-06-04 08:52:45

标签: jquery ajax

最终更新

我知道它有效(或至少我到目前为止所做的所有测试都有效)

这就是我设置它的方式,不确定它是对还是错。 :)我会将你的答案标记为正确,因为如果不是你的帮助,我不会做这样的事情。非常感谢。

var CommentClick = function() {
    $('.ReadMore').on('click', function() { 
        var CommentID = $(this).attr('id');
        FoundComment(CommentID); 
        $( ".ReadMore" ).off( "click");
    }); 
}

var FoundComment = function(JsonComment){
    var RequestedID = JsonComment;
    var CommentRequest = $.ajax({
        url: '/feedback',
        data: { CommentID: RequestedID },
        type: "POST",
        success: function(reply) {
            CommentData(reply); //Send JSON data to function for display
        } //End of success callback   
    }); //End of AJAX
}

var CommentData = function(SeletedComment) {
    var JsonData = $.parseJSON(SeletedComment); //Parse requested JSON data

    //Each needed data asigned to its own var
    var Comment = JsonData.Comment; 
    var Stars = JsonData.Stars;
    var User = JsonData.User;

    $('.FeedBackCommentFull').html('<span class="CloseComment shadow raised">CLOSE ME</span>');
    $('.FeedBackCommentFull').append('<div><span id="FeedBackUser">User: '+User+'</span> <span id="FeedBackStars"></span></div>');
    $('.FeedBackCommentFull').append('<span id="FeedBackComment">'+Comment+'</span>');
    $('.FeedBackCommentFull').slideToggle(700,"easeOutBounce");

    $('#FeedBackStars').raty({
        size: 16,
        path: 'assets/imgs/raty',
        score: Stars,               
        readOnly: true
    });

    $(' .CloseComment ').click(function() {
        $('.FeedBackCommentFull').slideToggle(700,"easeOutBounce");
        $( ".ReadMore" ).on("click", CommentClick() );   

    });
}

CommentClick(); 

更新3

这是我目前的代码:

 var DisplayMyComments = function(){
    var self = this;

    this.validCommentRequest = false;
    this.CommentRequest = {done : false};
    // Your clickhandler, named 'test' before
    this.clickHandler = function(event){
        var RequestedID = $(this).attr('id'); //Get ID of clicked div tag
        self.CommentRequest = $.ajax({
            url: '/feedback',
            data: { CommentID: RequestedID },
            type: "POST",
            success: function(reply) {
                self.validCommentRequest = true;
                var JsonData = $.parseJSON(reply); //Parse requested JSON data

                //Each needed data asigned to its own var
                var Comment = JsonData.Comment; 
                var Stars = JsonData.Stars;
                var User = JsonData.User;

                $('.FeedBackCommentFull').html('<span class="CloseComment shadow raised">CLOSE ME</span>');
                $('.FeedBackCommentFull').append('<div><span id="FeedBackUser">User: '+User+'</span> <span id="FeedBackStars"></span></div>');
                $('.FeedBackCommentFull').append('<span id="FeedBackComment">'+Comment+'</span>');
                $('.FeedBackCommentFull').slideToggle(700,"easeOutBounce");

                $('#FeedBackStars').raty({
                    size: 16,
                    path: 'assets/imgs/raty',
                    score: Stars,               
                    readOnly: true
                });

            } //End of success callback   
        });
    }

    $('.ReadMore').on('click', self.clickHandler);

    $.when(self.CommentRequest).done(function() {
        if(!self.validCommentRequest)return;
        if ($('.FeedBackCommentFull').is(':visible')) {
            $('.ReadMore').off('click', self.clickHandler);
            console.log( 'test...off' );
        }

        $(' .CloseComment ').click(function() {
            $('.FeedBackCommentFull').slideToggle(700,"easeOutBounce");
            $('.ReadMore').on('click', self.clickHandler);
            console.log( 'test...on' );
        });
    }); //End of When       
}
DisplayMyComments();

更新2

这就是我目前使用的,

var DisplayMyComments = function(){
    var self = this;
    //var CommentRequest; <- try this, did not seem to change the error
    this.CommentRequest = {done : false};
    // Your clickhandler, named 'test' before
    this.clickHandler = function(event){
                    var RequestedID = $(this).attr('id'); //Get ID of clicked div tag
        self.CommentRequest = $.ajax({
            url: '/feedback',
            data: { CommentID: RequestedID },
            type: "POST",
            success: function(reply) {
                var JsonData = $.parseJSON(reply); //Parse requested JSON data

                //Each needed data asigned to its own var
                var Comment = JsonData.Comment; 
                var Stars = JsonData.Stars;
                var User = JsonData.User;

                $('.FeedBackCommentFull').html('<span class="CloseComment shadow raised">CLOSE ME</span>');
                $('.FeedBackCommentFull').append('<div><span id="FeedBackUser">User: '+User+'</span> <span id="FeedBackStars"></span></div>');
                $('.FeedBackCommentFull').append('<span id="FeedBackComment">'+Comment+'</span>');
                $('.FeedBackCommentFull').slideToggle(700,"easeOutBounce");

                $('#FeedBackStars').raty({
                    size: 16,
                    path: 'assets/imgs/raty',
                    score: Stars,               
                    readOnly: true
                });

            } //End of success callback   
        });
    }

    $('.ReadMore').on('click', self.clickHandler);

    $.when(self.CommentRequest).done(function() {
        if ($('.FeedBackCommentFull').is(':visible')) {
            $('.ReadMore').off('click', self.clickHandler);
            console.log( 'test...off' );
        }

        $(' .CloseComment ').click(function() {
            $('.FeedBackCommentFull').slideToggle(700,"easeOutBounce");
            $('.ReadMore').on('click', self.clickHandler);
            console.log( 'test...on' );
        });
    }); //End of When       
}
DisplayMyComments();

很多,非常感谢您给予我的帮助。 :)


更新:

这就是我所做的,但由于某种原因,单击按钮时没有任何反应?

      var DisplayMyComments = function() { 
    var self = this;

    $('.ReadMore').on('click', self.clickHandler);

    this.clickhandler = $('.ReadMore').on('click', function(event) {
        var RequestedID = $(this).attr('id'); //Get ID of clicked div tag
    });

        this.CommentRequest = $.ajax({
            url: '/feedback',
            data: { CommentID: RequestedID },
            type: "POST",
            success: function(reply) {
                var JsonData = $.parseJSON(reply); //Parse requested JSON data

                //Each needed data asigned to its own var
                var Comment = JsonData.Comment; 
                var Stars = JsonData.Stars;
                var User = JsonData.User;

                $('.FeedBackCommentFull').html('<span class="CloseComment shadow raised">CLOSE ME</span>');
                $('.FeedBackCommentFull').append('<div><span id="FeedBackUser">User: '+User+'</span> <span id="FeedBackStars"></span></div>');
                $('.FeedBackCommentFull').append('<span id="FeedBackComment">'+Comment+'</span>');
                $('.FeedBackCommentFull').slideToggle(700,"easeOutBounce");

                $('#FeedBackStars').raty({
                    size: 16,
                    path: 'assets/imgs/raty',
                    score: Stars,               
                    readOnly: true
                });

            } //End of success callback   
        }); //End of AJAX request for User Comment


        //When AJAX request is complete / done, load click event for close button
        $.when (self.CommentRequest).done(function() {
            if ($('.FeedBackCommentFull').is(':visible')) {
                $('.ReadMore').off('click', self.clickHandler);
                //$('body').off('click', '.ReadMore', test);
                ///$('.ReadMore').css("visibility","hidden");
                //console.log( 'test...off' );
            }

            $(' .CloseComment ').click(function() {
                $('.FeedBackCommentFull').slideToggle(700,"easeOutBounce");
                $('.ReadMore').on('click', self.clickHandler);
                //$('body').on('click', '.ReadMore', test);
                //console.log( 'test...on' );
                //$('.ReadMore').css("visibility","visible");
            });
        }); //End of When

    //}); //End of on click for ReadMore link

} //End of function

我有一个完全(几乎)工作的JQuery代码。我正在为我的网站构建一个评论部分,在点击“阅读更多”按钮(div标签)后,将带有AJAX加载数据的div标签加载/滑动到视图中。,=

我遇到的问题是使用加载此代码的点击按钮进行开/关调用。因为我的网站是RWD构建的,所以容器元素在某些时候会显示加载此div的“read more”按钮。所以我要做的是,当AJAX内容div是可移动的时候,用'off'将click事件移到我的'read more'按钮。

这是我的整个代码部分,

 $('.ReadMore').on('click', function(event) {

    var RequestedID = $(this).attr('id'); //Get ID of clicked div tag
    var CommentRequest = $.ajax({
        url: '/getusercomments',
        data: { CommentID: RequestedID },
        type: "POST",
        success: function(reply) {
            var JsonData = $.parseJSON(reply); //Parse requested JSON data

            //Each needed data asigned to its own var
            var Comment = JsonData.Comment; 
            var Stars = JsonData.Stars;
            var User = JsonData.User;

            $('.FeedBackCommentFull').html('<span class="CloseComment shadow raised">CLOSE ME</span>');
            $('.FeedBackCommentFull').append('<div><span id="FeedBackUser">User: '+User+'</span> <span id="FeedBackStars"></span></div>');
            $('.FeedBackCommentFull').append('<span id="FeedBackComment">'+Comment+'</span>');
            $('.FeedBackCommentFull').slideToggle(700,"easeOutBounce");

            $('#FeedBackStars').raty({
                size: 16,
                path: 'assets/imgs/raty',
                score: Stars,               
                readOnly: true
            });

        } //End of success callback   
    }); //End of AJAX request for User Comment

    //When AJAX request is complete / done, load click event for close button
    $.when (CommentRequest).done(function() {
        if ($('.FeedBackCommentFull').is(':visible')) {
            $('.ReadMore').off('click');
            console.log( 'test...off' );
        }

        $(' .CloseComment ').click(function() {
            $('.FeedBackCommentFull').slideToggle(700,"easeOutBounce");
            $('.ReadMore').on('click');
            console.log( 'test...on' );
        });
    }); //End of When

}); //End of on click for ReadMore link

我从中获取数据的URL使用PHP Slim获取所有提交的注释的列表,JSON对这些数据进行编码,我对其进行排序和显示。这一切都有效,它甚至从“阅读更多”按钮中删除了“点击”事件,但由于某种原因,它不会在选择“关闭”按钮后添加点击事件。

现在我也尝试过,将“Read More”点击进入var然后调用它,就像这样,

   var test = $('.ReadMore').on('click', function(event) { .......

然后尝试加载它,

    $.when (CommentRequest).done(function() {
        if ($('.FeedBackCommentFull').is(':visible')) {
            $('.ReadMore').off('click', test);
            console.log( 'test...off' );
        }

        $(' .CloseComment ').click(function() {
            $('.FeedBackCommentFull').slideToggle(700,"easeOutBounce");
            $('.ReadMore').on('click', test);
            console.log( 'test...on' );
        });
    }); //End of When

但是当我这样做时,它不会删除点击事件,而是 Uncaught TypeError: undefined is not a function

我也尝试将开/关指定给身体,比如,

                    if ($('.FeedBackCommentFull').is(':visible')) {
            $('body').off('click', '.ReadMore', test);
            console.log( 'test...off' );
        }

        $(' .CloseComment ').click(function() {
            $('.FeedBackCommentFull').slideToggle(700,"easeOutBounce");
            $('body').on('click', '.ReadMore', test);
            console.log( 'test...on' );
        });

与之前的测试效果相同,所以我做错了什么?

非常欢迎所有人的帮助。

感谢。

1 个答案:

答案 0 :(得分:1)

正如Su4p所说,你有把Handler放在var中,而不是整个绑定(它只返回给定Selector的jQuery Object)。 所以你必须替换

var test = $('.ReadMore').on('click', function(event) { .......

var test = function(event){...}
$('.ReadMore').on('click', test)

另外,请确保在范围内定义测试或最终调用处理程序var的任何内容,以便调用可以访问它。最好的方法是将var中的所有内容封装起来,保留函数的范围,e.q。与

var self = this;

直接在开始时,您可以稍后访问每个var&amp;函数由范围前缀&#34; self。&#34; 类似的东西:

var MyNamespace = function(){
    var self = this;
    this.validCommentRequest = false;
    this.CommentRequest = {done : false};
        // Your clickhandler, named 'test' before
    this.clickHandler = function(event){
        self.CommentRequest = $.ajax({
            // your request here
            success : function (data){
                self.validCommentRequest = true;
            }
        })
    }


    $('.ReadMore').on('click', self.clickHandler);

    $.when(self.CommentRequest).done(function() {
        if(!self.validCommentRequest)return;
        if ($('.FeedBackCommentFull').is(':visible')) {
            $('.ReadMore').off('click', self.clickHandler);
            console.log( 'test...off' );
        }

        $(' .CloseComment ').click(function() {
            $('.FeedBackCommentFull').slideToggle(700,"easeOutBounce");
            $('.ReadMore').on('click', self.clickHandler);
            console.log( 'test...on' );
        });
    }); //End of When       
}

我希望这能让您对如何构建代码有所了解。这样做的好处是也不会污染全局命名空间。