无论返回false,Onclick都会访问该链接

时间:2016-06-21 14:59:11

标签: javascript

我试图通过链接点击提交ajax功能,我正在使用onclick如下:

<a href="<?php echo SITE_URL; ?>watchlist/remove/<?php echo System::escape($this->item->item_id); ?>" onclick="manage_watchlist(); return false;" id="watchlist">
    Remove From Watchlist
</a>

和我的职能:

var manage_watchlist = function(e)
{
    alert("ff");
    e.preventDefault();

    $.ajax({
        url: $(this).attr('href'),
        type: 'post',
        dataType: 'json',
        success: function(data)
        {
            if(data.success)
            {
                if($(this).hasClass("remove"))
                {
                    $(this).text("Add to Watchlist");
                    $(this).removeClass("remove").addClass("add");
                    $(this).attr('href', '<?php echo SITE_URL; ?>watchlist/add/<?php echo System::escape($this->item->item_id); ?>');
                }
                else
                {
                    $(this).text("Remove from Watchlist");  
                    $(this).removeClass("add").addClass("remove");
                    $(this).attr('href', '<?php echo SITE_URL; ?>watchlist/remove/<?php echo System::escape($this->item->item_id); ?>');
                }
                $('#watch_success_message').html(data.success + alert_close).show();
            }
            else
            {
                $('#watch_error_message').html(data.error + alert_close).show();
            }
                <!-- hide loading icon -->
                $('.ajloading').hide();
        },
        error: function()
        {
            <!-- hide loading icon -->
            $('.ajloading').hide();
        }
    });
    return false;
}

我已在功能中发出警报,因此我的功能正在运行,但由于某种原因它仍在访问该链接?

4 个答案:

答案 0 :(得分:3)

您需要使用内联事件处理程序传递事件。

onclick="manage_watchlist(event);"

或者更好的是,转储内联事件并使用jQuery来附加事件。

答案 1 :(得分:0)

对于内联事件e.preventDefault();&#34;阻止&#34;返回false。

仅使用return false;

答案 2 :(得分:0)

做这样的事情:

<a href="<?php echo SITE_URL; ?>watchlist/remove/<?php 
echo System::escape($this->item->item_id); ?>" id="watchlist">
    Remove From Watchlist
</a>

//JS
$(document).ready(function(){
   $('#watchlist').click(function(e){
     var $this = $(this); //**this** is the anchor
     e.preventDefault(); //e is click event.
     $.ajax({//use $this when you mean the anchor
        //**this** here is $.ajax
        //...
        //your code here
     });//$.ajax
   });//$('#watchlist').click
});//$(document).ready

答案 3 :(得分:0)

当您将代码放入字符串中以进行onclick时,它不会像您认为的那样起作用。它的行为类似于:

function(event) {
    manage_watchlist();
}

这就是你必须在html onclick中将事件对象传递给你的函数的原因。

onclick="manage_watchlist(event);"

看起来像

function(event) {
    manage_watchlist(event);
}