This is how I can select all links whose href's don't start with a #
:
$('a:not([href^="#"])')
But how can I determine whether a link has a href that starts with a hash tag or not AFTER it's clicked? This fails:
$('a').on('click', function() {
if($(this).is('[href^="#"])')) {
alert('No hash');
}
});
You removed the :not()
from your selector. Put it back and it should work.
if($(this).is('a:not([href^="#"])')) {
DEMO: http://jsfiddle.net/8An48/
Or better...
if (this.getAttribute("href").charAt(0) !== "#") {
DEMO: http://jsfiddle.net/8An48/1/
Or use event delegation from the nearest ancestor that contains all the a
elements being targeted.
$('body').on('click', 'a:not([href^="#"])', function() {
alert('No hash');
});
Try:
$('a').on('click', function() {
if(($(this).attr('href').substr(0,1)) != '#') {
alert('No hash');
}
});
$('a').on('click', function() {
if($(this).attr("href").indexOf("#") === -1) {
alert('No hash');
}
});
Explanation
$(this).attr("href")
- gets the value of the href attribute of the clicked link
.indexOf("#")
- this will return the position of string B if string A contains it. Otherwise it returns false
=== -1
- the triple equals and the -1
ensures that this is 100% false (and not equal to a string or a number)
You can use .filter()
.
$('a').filter(function(){
return this.href.slice(0, 1) !== '#';
}).addClass('does-not-start-with-hash');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.