2011-02-25 106 views
1

嘿傢伙, 下面的代碼工作正常......我添加了#wpf-wrapper哈希到#wpf-wrapper裏面的所有鏈接。jquery:將#hash添加到所有鏈接,如果它還沒有?

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

但是,如果存在已經具有例如href="#"我不想再添加一個。爲什麼下面的代碼不工作?

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

突然沒有我的鏈接獲得這個#wpf-wrapper添加?

+0

是否有一個原因,你想在點擊處理程序而不是預先做到這一點? – user113716 2011-02-25 14:56:01

回答

5

這個選擇是錯誤的

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

應該用attribute contains selector以適當的:not()選擇

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

你打敗了我。 – 2011-02-25 14:42:51

1

這裏的另一種方式是這樣的:

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

您可以使用本機hash物業a元素來設置它,而不是使用jQuery的.attr()方法。


如果你單擊處理程序內這樣做的原因,是一個.each()不起作用,很可能是你正在運行的代碼加載DOM之前。

如果是這樣,這樣做:

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

如果你動態創建的元素,添加散列正在被創建時。

相關問題