检查 URL 时触发操作

时间:2021-04-20 07:13:59

标签: javascript jquery

我正在以 HTML 格式创建指向同一页面上的部分的链接。默认情况下,它们不可见显示:无。我希望当我的用户点击包含 id 的链接(URL)时,它应该设置 display : block。例如,openingwindow.location.href 包含 #opening 时的 id,因此内容应该是可见的。用户只需在浏览器中点击 mydomain#opening,无需点击 <a>#id

HTML

<p id="opening">Hyperlinks are utilized by a web browser to move from one page to another...</p>
<p>My Name is XYZ...</p>

CSS

#opening {display : none;}

1 个答案:

答案 0 :(得分:2)

试试这个:-

<a href="#opening" onclick="$('#opening').css({display: 'block'})" >Take me to the opening paragraph.</a>

$("a").click(function() { 
   var href =  $(this).attr("href"); 
   href = href.replace("#",""); 
   $("#"+href).css("display","block"); 
})

在窗口加载时:-

$(document).ready(function() {
 var hash = window.location.hash.substr(1);
 if (hash) {
  $("#"+hash).css("display","block"); 
  }
});