防止默认停止 window.location.href 工作

preventDefault stops window.location.href from working

本文关键字:href 工作 location 默认 window      更新时间:2023-09-26

我的网站上有两个广告,其中一个使用脚本来解析网站上的所有链接并对其进行preventDefault()......这使我无法在任何链接上使用 preventDefault(),因为它只能完成一次......但是,在过去,我已经能够使用 return false 解决此问题。由于某种原因,它不适用于jQuery UI自动完成功能(请参阅下面的代码)。

如果我关闭广告,脚本工作正常。否则它只是重新加载页面,因为return false;似乎不起作用......

脚本我无法更改:

$(document).ready(function() {  
    $('a').on('click', function(e) {
        e.preventDefault();
        // stuff
    });
)};

我的脚本:

$search.autocomplete({
  source: function(request, response){
    $url = "suggestions/";
    $.get($url, {data:request.term}, function(data){     
        response($.map(data, function(item) {
        return {                
            label: item.movie_name,
            id: item.movie_id
        }
        }))
    }, "json");
  },
  minLength: 2,
  dataType: "json",
  cache: true,
  focus: function(event, ui) {
    return false;
  },
  select: function(event, ui) {
    window.location.href = ('/id/'+ ui.item.id +'/'+ ui.item.label +'/');
    return false;
  }
});

我找到了一个有效的解决方案:

  select: function(event, ui) {
     $('.ui-autocomplete a').attr('href', '/id/'+ ui.item.id +'/'+ ui.item.label +'/');     
  }

解释:jquery-ui-autocomplete 函数创建一个链接 ()-标签列表,通常你会使用 preventDefault() 来阻止浏览器进入 href 地址,因为在我的情况下这是不可能的,我尝试使用 return false 代替,但由于在这种情况下这也不起作用,我终于想到了,为什么不将链接标签 href 更改为正确的 url 而不是停止操作, 哪个有效!