问题
In a list I have a few links:
<ul class="dropdowner" id="coll-filter">
<li><a href="#black">Black</a></li>
<li><a href="#white">White</a></li>
<li><a href="#blue">Blue</a></li>
</ul>
Another output I have uses + instead of # in the url Ie:
<ul class="dropdowner" id="coll-filter">
<li><a href="+black">Black</a></li>
<li><a href="+white">White</a></li>
<li><a href="+blue">Blue</a></li>
</ul>
If I click the link White then "#white" is inserted into my URL. (mydomain.com/#white) I want to avoid duplicates so is there a way to check if "#white" already exist in URL and if so don't allow the link to be clicked.
回答1:
Use the Javascript window.location.hash
call to determine what the current URL anchor is and base your logic on that:
$('.dropdowner a').click(function (event) {
if ($(this).attr('href')==window.location.hash){
return false;
}
});
回答2:
This should do what you're looking for - location.hash gives you the current anchor hash from the URL
$(function(){
$('ul.dropdowner').find('a').click(function() {
if ($(this).attr('href') == location.hash) {
return false;
}
}
}
回答3:
This act like you said by default. if the url contain #value1 of any kind it will not duplicate and the url can never looks like : #value1#value1
回答4:
The following will both disable a link which matches the component of the URL after the # or + as well an enable any previously disabled links:
$('.dropdowner a').on('click', function() {
var url = window.location,
tag = url.split('+'),
hash = window.location.hash,
supress = function(term) {
$('.dropdowner a[href=' + term + ']').bind('click', false);
};
$('.dropdowner a').unbind('click', false);
if (hash) {
supress(hash);
} else if (typeof tag !== 'undefined') {
supress('+' + tag);
}
});
See:
- http://api.jquery.com/bind/
- http://api.jquery.com/unbind/
- https://developer.mozilla.org/en-US/docs/DOM/window.location#Properties
来源:https://stackoverflow.com/questions/12903961/check-if-url-contains-href-of-link-i-already-clicked