使用jquery更改URL

时间:2015-08-11 14:34:03

标签: javascript jquery

你能解释一下。

为什么返回,只返回第一个数据属性 - “link-1.html”,即使我点击第二个链接

<a class="project-link" href="link-1.html" data-url="link-1.html">
<a class="project-link" href="link-2.html" data-url="link-2.html">

var toUrl = $('.project-link').attr('data-url');
  $('a').click(function() {
  window.location.hash = toUrl;

});

此类操作的含义 - 我的链接通过Ajax打开,但我想在浏览器中显示URL。

我想让它成为behance,如果你点击卡片组合,它们通过Ajax在同一个窗口中显示,但它也留下了直接吸引链接的可能性。这就是我想要在浏览器地址栏中显示的URL

的原因

4 个答案:

答案 0 :(得分:2)

您必须按this

获取当前目标网址
$('a').click(function() {
   var toUrl = $(this).data('url'); // use this as current target
   window.location.hash = toUrl;
});

我建议您在(仅)检索数据属性而不是.data()时使用.attr()

Demo

答案 1 :(得分:1)

  

.attr(attributeName)
  返回:字符串
  说明:获取价值   在匹配元素集合中第一个元素的属性

$('.project-link')匹配多个元素。因此,$('.project-link').attr('data-url')将返回集合中第一个元素的data-url属性值。

要解决此问题,您必须在获取属性时维护所点击元素的context,并使用this关键字执行此操作。

如果您已经有其他事件侦听器附加到该元素并且您不希望它们触发 - 虽然在重定向用户时ajax调用将中止 - 您可以使用event.stopImmediatePropagation()

$('a').on('click', function( event ) {
    event.stopImmediatePropagation();
    window.location.hash = $(this).data('url'); //this here refers to the element that was clicked.
});

答案 2 :(得分:0)

$('a[data-url]').click(function() {
     window.location.href = $(this).data("url");
});

答案 3 :(得分:0)

您可能想尝试一下:

$('.project-link').click(function(){
     window.location.hash = $(this).data('url');
});