当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - How to block a link if its href contains a hash?

问题描述:

if condition working but else condition not working.

 (function($){

$(".single-product a").on("click", function(e){

var link = $(".single-product a").attr("href");

if(link == "#"){

e.preventDefault();

}else{

return true;

}

});

}(jQuery));

网友答案:

have you tried this? using prop on the attr it might be your jquery library is higher

$(document).on("click",".single-product a", function(e){
     var link = $.trim($(this).prop("href"));  
     (link == "#") ?  e.preventDefault() : '';
 });
网友答案:

With the attribute contains selector [name*=”value”]:

$('.single-product a[href*="#"]').on('click', function (e) {
  e.preventDefault();
});
<div class="single-product">
  <a href="https://www.google.com#foo">With #</a>
</div>

<div class="single-product">
  <a href="https://www.google.com">Without #</a>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
分享给朋友:
您可能感兴趣的文章:
随机阅读: