Javascript 使用jquery禁用href属性

Javascript 使用jquery禁用href属性,javascript,jquery,html,href,Javascript,Jquery,Html,Href,我想禁用a链接以刷新页面(即转到href链接)。但是我想根据href值修改url 目前,我正在尝试这个 $('.advertPP').click(function() { event.preventDefault(); location.href = link.attr("href"); }); HTML链接 <a href="products?id=<?php echo $item_id; ?>" class="advertPP">Link</a

我想禁用
a
链接以刷新页面(即转到href链接)。但是我想根据
href
值修改url

目前,我正在尝试这个

$('.advertPP').click(function() {
    event.preventDefault();
    location.href = link.attr("href");
});
HTML链接

<a href="products?id=<?php echo $item_id; ?>" class="advertPP">Link</a>


由于两者都在同一页面上,因此我不希望刷新页面,但希望url按照href值进行修改。

我注意到您没有向函数传递
事件
对象。应按如下方式传递对象:

$('.advertPP').click(function(event) {
                            //^^^^^ pass the event object
    event.preventDefault();
    $(this).attr("href", "http://...");
});

检查document.URL和$(this.attr('href')是否相同,然后设置新URL并返回false。 如果两者不同,则重定向到页面

$('a').click(function() {
    var currentUrl = document.URL
    if ($(this).attr('href') == currentUrl) {
        $(this).attr('href', 'http://www.google.com');
        return false;
    }
})
您的代码充满了(逻辑)错误

可能您希望页面在不刷新的情况下更改内容,因此需要AJAX,下面是一个示例:

$('.advertPP').click(function(event) {
    event.preventDefault();
    $.ajax({
        url: this.href,
        success: function(data) {
            //if the loaded page is a full html page, replace the HTML with the data you requested
            $("body").html(data); //make sure your data has only body contents, either you can replace the full HTML even if it is a bad practice $("html").html(data);
        }
    });
});

那么,是否要将链接的行为替换为链接的行为?是的,我希望在不刷新设置
位置的情况下更改url。href
将导致页面重新加载。因此,您可以提供其他方法吗?当然可以-使用。$(“链接”)将指向什么?也许你想写$(这个;)是的,那是我的错。谢谢你的提醒,嗯,我真的不明白你的代码,即使它现在是正确的<代码>$(this.attr(“href”、“…”)只会更改链接的属性,它不会更改/重新加载页面,而OP只想更改
href
属性,但会阻止页面重新加载。设置了
位置。href
,所以我想他想更改页面:p我应该用数据替换什么,不明白吗?这取决于ajax请求返回的内容。如果它是一个完整的HTML页面,包括
标记,那么您可以使用
$(“HTML”).HTML(数据)
而不是
$(“body”).HTML(数据)
,即使这不是一个很好的实践,但您的代码工作正常,唯一的问题是我需要的id在单击两次后返回,这意味着当我单击两次时id会更新,否则,它会显示前一次单击第二次之前要等待多长时间?Ajax是异步的,因此页面将继续执行,但当数据完全加载时将调用回调。尝试单击一次并等待几秒钟,它应该可以工作。你说“id”是什么意思?是的,但这取决于很多事情,从连接速度到服务器响应速度。因此,真正的答案是不,这是不可能的(至少在没有大量工作的情况下)
$('.advertPP').click(function(event) {
    event.preventDefault();
    $.ajax({
        url: this.href,
        success: function(data) {
            //if the loaded page is a full html page, replace the HTML with the data you requested
            $("body").html(data); //make sure your data has only body contents, either you can replace the full HTML even if it is a bad practice $("html").html(data);
        }
    });
});