超链接标记“<a>"无法在html页面中工作

hyperlink tag "<a>" not working in html page

本文关键字:html 工作 gt lt 超链接 quot      更新时间:2023-09-26

我的html页面中有以下代码:

    <body>
    <div align="center">
      <a href="../index.html">
      <img border="0" src="banner1.jpg" width="800" height="120" alt="Ecommerce Knowledge Base">    </a>
      <div style="background-image:url(Heading%20Background.jpg); width:800px">
      <a href="../index.html" style="position:relative; left:-130px">HOME</a>
      <a href="" style="position:relative; left:-65px" id="planning">PLANNING</a>   
    </div>
    ...
    ...
    ...
    </body>

超链接HOME链接到index.html页面,该页面位于包含该html页面的文件夹的根文件夹中。但单击此超链接后不会发生任何事情。即使是链接到同一页面的banner也不起作用。

奇怪的是,这两个超链接以前都工作得很好,直到我在页面中更改了一些"jquery"代码。但我不确定这一变化是如何影响这一点的。请帮忙。这些是从进行的代码更改

    <script> 
    $(document).ready(function(){
      $("#planning").click(function(e){
        $("#planning_panel").slideToggle("slow");
        e.preventDefault()
       });
     });
    </script>

至:

    <script> 
    $(document).ready(function() {
     $(document).on('click',function(e) {
  e.preventDefault();
   var $panel = $("#planning_panel");
   if (e.target.id === 'planning') {
     $panel.slideToggle('slow');
   } else {
     $panel.slideUp('slow');
   }
        });
      });
     </script>

两个脚本都运行良好,唯一的问题是一旦进行了更改,超链接就停止了工作。

这个新代码:

$(document).ready(function() {
  $(document).on('click',function(e) {
     e.preventDefault();
     // ...
   });
});

告诉浏览器,当出现弹出到文档的单击时(大多数单击最终都是这样,除非您从更深层的处理程序调用stopPropagation(,浏览器应阻止默认操作。单击链接的默认操作是跟随链接。

解决方案是,仅当您希望阻止单击操作时才调用e.preventDefault();。以下是我可能重新编译代码的方法:

$(document).ready(function() {
  $(document).on('click',function(e) {
    var $panel = $("#planning_panel");
    if ($(e.target).closest("#planning")[0]) {
      // Click is on the planning link, toggle the panel and prevent the default
      $panel.slideToggle('slow');
      e.preventDefault();
    } else {
      // Not on the planning link, slide the panel up
      $panel.slideUp('slow');
    }
  });
});

实时示例|源(我已在HOME链接上将../index.html更改为http://stackoverflow.com,但除此之外,唯一的更改是代码(

只有在#planning链接上,我们才会阻止默认的点击操作。

附带说明:我使用了closest而不是检查e.target.id,因为它更健壮。对于您的标记来说,这并不是绝对必要的,但如果您稍微更改了标记(添加了spanem或其他什么(,您就会需要它,所以它有利于健壮性。

$(document).on('click',function(e) {
  e.preventDefault();

它将阻止任何单击默认行为。

$(document).on('click',function(e) {

这应该像

$(document).on('click', '#planning', function (e) {

这应该是问题所在:

$(document).on('click',function(e) {
  e.preventDefault();

您阻止所有对文档的点击,因此链接无法正常工作。将第一行更改为

$('#planning').on('click', function(e){
  e.preventDefault();

顺便说一句:我真的不明白你的功能是什么。

<script> 
$(document).ready(function() {
 $(document).on('click',function(e) {
e.preventDefault();
var $panel = $("#planning_panel");
if (e.target.id == 'planning') {
 $panel.slideToggle('slow');
} else {
 $panel.slideUp('slow');
}
    });
  });

使用此配对