jQuery / JS - 如何排除<a> with specific href in conditions?

时间:2016-05-18 12:36:58

标签: javascript jquery preloader

I'm trying to exclude specific <a> into if statement, basing on their href values. More specifically I'm showing a preloader div when whatever <a> is clicked except for those triggering javascript or containing #. This makes my users see a nice screen while waiting for page load.

I've written this little js things:

$('a').click(function() {
  var href = $(this).attr('href');

  //my conditions
  if ((href != '#') || (href != 'javascript:void(0);')) {
    $('#preloader').fadeIn("fast");
  }
});

//Showing preloader
$(window).load(function() {
  $('#preloader').fadeOut("slow");
});

My statement works excluding links containing # but for those with javascript:void(0);, it doesn't instead. This is my problem. What am I doing wrong? Is there an error in statement or in values?

2 个答案:

答案 0 :(得分:1)

我可以想到两种直接的方法来解决给定代码的问题:

  1. 您的条件不正确。 if((href != '#') || (href != 'javascript:void(0);'))应为if(href != '#' && href != 'javascript:void(0);')

  2. 最理想的是,从查询本身中排除不相关的元素:

  3. $('a').not('[href="#"]').not('[href="javascript:void(0);"]).click(function() {
        $('#preloader').fadeIn("fast");
    });
    

    请参阅jQuery的Attribute Not Equal Selector

答案 1 :(得分:0)

这个答案可以帮助某人......以及另一种检查方式

if($(this).is(':not([href^="#"]):not([href^="javascript:"])')){
   $('#preloader').fadeIn("fast");
}

&#13;
&#13;
$('a').on('click',function(e){
	e.preventDefault();
	if($(this).is(':not([href^="#"]):not([href^="javascript:"])')){
  	alert('Good');
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="javascript:void(0);">
  click
</a><br />
<a href="#">
  click
</a><br />

<a href="go">
  click
</a><br />
&#13;
&#13;
&#13;