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.
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;
}
});
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;
}
}
}
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
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:
来源:https://stackoverflow.com/questions/12903961/check-if-url-contains-href-of-link-i-already-clicked