繁体   English   中英

从不包含该元素的ID的链接跳转到另一个页面上的元素

[英]Jump to an element from a link not containing that element's id and on a different page

必备知识:

在我的网站页脚中,有一些链接可以将用户重定向到该网站的公司页面,例如www.example.com/company.html#first。

单击此链接将触发默认的浏览器行为,即它将重定向到www.example.com/company.html#first并显示id =“ first”的div。

但是在我的company.html的dom中,没有id =“ first”的div(由于种种原因,我无法将ID提供给相关的div,但这是一个单独的问题)。 此外,由于某些功能,我必须使用url的哈希值 ,因此必须将其保留为#first

题:

因此,我的问题是,是否可以将另一个div引入视图-div的父元素(具有可用的id ),我无法在单击页脚链接时如上所述提供该id。 也欢迎提出建议!

由于您是在指示您有权访问jQuery,因此您可以编写脚本以在出现以下情况后更改它们:

var link1 = $('a[href="http://www.example.com/company.html#first"]');
$(link1).attr('href','http://www.example.com/company.html#mydiv');

这样,您将更改您真正希望它指向的URL。 您将为每个人做类似的事情。

可能感兴趣的是为页脚中的链接提供后备URL,该后备URL显示为data-*属性。 例如

<a href="www.example.com/company.html#first" data-fallback="www.example.com/company.html#first-parent" title="First">First</a>

在jQuery中,您可以执行以下操作(未经测试):

$("a").click(function(e) {
  if (window.location.hash) {
    // Don't follow the link initially
    e.preventDefault();

    var url = this.href,
      // Borrowed from: http://stackoverflow.com/a/4426201/1150683
      el = $(url.substring(url.indexOf('#') + 1));

    // If element exists
    if (el.length > 0) {
      window.location.href = url;
    } else {
      window.location.href = $(this).data("fallback");
    }
  }
});

因此,我确实解决了自己的问题,但是只能通过对可用的URL哈希进行硬编码来解决。 这有点脏,脚本会在每个页面上调用,但是我认为这是我现在要使用的。 我像这样使用$(document).ready():

$(document).ready(function() {
if (location.pathname.split('/')[1] === 'company.html' && $.inArray(location.hash.split('#')[1], ['first', 'second', 'third']) > -1) {
  $('#parent').get(0).scrollIntoView();
}
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM