代码之家  ›  专栏  ›  技术社区  ›  Ramesh Diego Lins de Freitas

在单击子元素(输入)时阻止父元素单击(a)事件[复制]

  •  0
  • Ramesh Diego Lins de Freitas  · 技术社区  · 6 年前

    我有一个 a 包装的标签,里面有一些内容。当该框单击时,它将重定向到其他页面。同时我还有 input type="button" 元素内部 包装器。还有这个 button 单击时必须重定向到单独的页面。

    到目前为止,我已经尝试了一些jquery方法,但都导致了失败。

    $(".wrapper").click(function(e) {
      if (e.target.className == "btn") {
        e.preventDefault();
        var link = $(this).find(".btn").attr('data-link');
        console.log(link);
        //window.location.href = link;
      }
    });
    a.wrapper {
      display: inline-block;
      height: 100px;
      width: 100px;
      border: 1px solid #333;
      background: #ddd;
      text-align: center;
    }
    
    a.wrapper * {
      display: inline-block;
      padding: 5px;
      margin: 3px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <a href="google.com" class="wrapper">
      <span>some content</span>
      <input type="button" class="btn" value="click me" data-link="yahoo.com" />
    </a>

    我怎样才能防止 当我单击 按钮 ?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Jeremiah Stillings    6 年前

    我不明白你的目标是什么? a是一个文本链接,而button是一个HTML元素,两者都会将您发送到某个地方。你为什么要把它们混在一起? btn的一个类非常通用,以至于许多web开发人员用它来设计整个品牌,然后用id为每个品牌添加风格 如果这确实是一个特殊的按钮,请尝试在css中使用#id。

    <form>
    <a href="https://www.google.com" class="wrapper"><span>some content</span></a>
    <button type="submit" class="btn" id="special_button" formaction="https://www.yahoo.com" >
    </form>
    

    #special_button {
      -webkit-transition-duration: 0.4s; /* Safari add all the browsers your targeting */
      transition-duration: 0.4s;
    }
    
    #special_button:hover {
      background-color: #4CAF50; /* Green */
      color: white;
    }