在网页中找不到由URL段标识的HTML部分

时间:2016-04-12 23:19:35

标签: javascript html hyperlink

如何在网页上找不到url片段标识的部分时通知用户?

实施例

website1包含:

<a href="/website2#foo"> bring me to the foo section of website2 </a>

和网站2包含:

<div id="foo"> I'm the foo section </div>

因此,如果我点击链接并且div的标识符不是“foo”而是“bar”,则网页会显示“foo section not found”之类的提醒。

上下文:我在html页面上公开了一个API的JSON响应,我希望JSON的属性链接到文档页面。如果未找到描述该属性的部分,则应建议更新文档。

更新:如果可能,不使用javascript框架

由于

2 个答案:

答案 0 :(得分:3)

这应该可以解决问题。

在website2的“onLoad”上,我检查url是否包含一个段,然后使用getElementById(segment)在文档中查找该Id ..

<html>
    <body onload="myFunction()">

        <h1>Hello World!</h1>

        <script>
        function myFunction() {

            var segment;

            if(window.location.hash){

               segment = window.location.hash.substring(1);

               if( document.getElementById(segment) == null ){

                   alert("html element with id "+segment+" not found");
               }
            }
        }

        </script>
    </body>
</html>

答案 1 :(得分:0)

您使用的是jQuery吗? 你不能用html或css来做这件事,但你可以用jQuery很容易地做到这一点,如下所示:

   $('.navigation a').on("click", function(){
      //This gets the href and splits it on "#". Grabs the value after "#"
      //Make sure to only have 1 # in a link
      var idToFind = $(this).attr("href").split("#")[1];

      //Check if a div with this ID exists
      if($('#'+idToFind).length > 0){
       //it has been found, you could turn the scrolling to the section into a neat animation here, if you want
      }
      else{
        //It has not found it. Alert.
        alert('"' + idToFind + '" section not found');
      }

  });

修改 这是一个vanilla js解决方案:

HTML:

<a href="#foo" onClick="checkSection(this.href)"> bring me to the foo section </a>

使用Javascript:

function checkSection(section){
 var idToFind = $(this).getAttribute("href").split("#")[1];
 //Get the element
 var element = document.getElementById(idToFind);

 //check if element exists
 if (typeof(element) != 'undefined' && element != null)
 {
   // exists.
 }
 else{
  //doesn't exist
  alert(idToFind + "doesn't exist");
 } 

}