<div>标签带有可点击的链接,其中包含<a> tag inside

时间:2018-07-24 01:00:23

标签: javascript html css html5

So I m using a tag with a whole block used as a link, it is a product display so you click it it goes to product page. Now on in that I created an tag as a button for a link to the cart page. So I have it working, but when i click the CART button both pages open the product and the cart. I know its doing that because the cart button is within the block that is a link. I did 2 versions and they both don't work! But how do I fix it ??

version1:

 <Div class="col-md-3" onClick="window.open('product.html');"  >
    <Div class="product-thumb">
      <h4>MacBook</h4>
      <img src="image/macbook_1-200x200.jpg" alt="Product">
      <p>Intel Core 2 Duo processor Powered by an Intel Core 2 Duo processor at speeds up to 2.1..</p>
      <p class="price">$3000 USD</p>
      <a href="cart.html;" class="btn btn-default"><i class="glyphicon glyphicon-shopping-cart"></i> Add to cart</a> 
  </Div>

Version2:

<Div class="col-md-3" onClick="window.open('product.html');"  >
    <Div class="product-thumb">
      <h4>MacBook</h4>
      <img src="image/macbook_1-200x200.jpg" alt="Product">
      <p>Intel Core 2 Duo processor Powered by an Intel Core 2 Duo processor at speeds up to 2.1..</p>
      <p class="price">$3000 USD</p>
      <a href="cart.html" class="btn btn-default"><i class="glyphicon glyphicon-shopping-cart"></i> Add to cart</a> </Div>
  </Div>

4 个答案:

答案 0 :(得分:1)

您可以使用stopPropagation。看不到您的代码不能百分百确定,但类似这样的东西:

$(a).click(function(event){
    event.stopPropagation();
});

答案 1 :(得分:1)

由于event bubbling,您需要使用event.stopPropagation()来避免这种行为。

    <Div class="col-md-3" onClick="window.open('product.html');">
      <Div class="product-thumb">
        <h4>MacBook</h4>
        <img src="image/macbook_1-200x200.jpg" alt="Product">
        <p>Intel Core 2 Duo processor Powered by an Intel Core 2 Duo processor at speeds up to 2.1..</p>
        <p class="price">$3000 USD</p>
        <a href="cart.html" onClick="event.stopPropagation()" class="btn btn-default"><i class="glyphicon glyphicon-shopping-cart"></i> Add to cart</a> </Div>
    </Div>

答案 2 :(得分:0)

您可以只使用10=namespaceonclick并在其中传递链接,

location.href

答案 3 :(得分:0)

您需要使用event.stopPropagation()阻止事件使DOM树冒泡。

<div class="col-md-3" onClick="window.open('product.html');"  >
    <div class="product-thumb">
      <h4>MacBook</h4>
      <img src="image/macbook_1-200x200.jpg" alt="Product">
      <p>Intel Core 2 Duo processor Powered by an Intel Core 2 Duo processor at speeds up to 2.1..</p>
      <p class="price">$3000 USD</p>
      <a href="cart.html" id="cartlink" class="btn btn-default"><i class="glyphicon glyphicon-shopping-cart"></i> Add to cart</a> </div>
  </div>
  <script>
  document.getElementById("cartlink").addEventListener("click", function(event){
    event.stopPropagation();
  });
  </script>