开发者

jquery: add #hash to all links if it doesn't already have one?

hey guys, the following code works fine... I'm adding a #wpf-wrapper hash to all links that are inside of #wpf-wrapper.

$('#wpf-wrapper a').live('click',function() {
    $(this).attr('href', $(this).attr('href') + "#wpf-wrapper");        
});

However 开发者_如何学Pythonif there is a link that already has e.g. href="#" I don't want to add another one to it. Why is the following code not working?

$('#wpf-wrapper a').not('#wpf-wrapper a[href="#"]').live('click',function() 
    $(this).attr('href', $(this).attr('href') + "#wpf-wrapper");        
});

Suddenly none of my links gets this #wpf-wrapper added?


This selector is wrong

$('#wpf-wrapper a').not('#wpf-wrapper a[href="#"]')

should be this using the attribute contains selector with a proper :not() selector

$('#wpf-wrapper a:not([href*="#"])')


Here's another way:

$('#wpf-wrapper a').each(function(){ 
    if( !this.hash ) this.hash = "#wpf-wrapper";
});

You can use the native hash property on the a element to set it instead of using jQuery's .attr() method.


If the reason you're doing this inside the click handler, is that an .each() doesn't work, it's likely that you're running the code before the DOM is loaded.

If so, do this:

$(function() {
    $('#wpf-wrapper a').each(function(){ 
        if( !this.hash ) this.hash = "#wpf-wrapper";
    });
});

If you're creating the elements dynamically, add the hash when they're being created.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜