簡體   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