2011-07-08 22 views
1

鏈接的點擊事件鏈接的相對attribut的價值我有很多的鏈接像這樣的不同版本屬性得到使用jQuery

<a href="#" class="buy" rel="WVSEU1Y">buy</a> 

我想rel屬性上點擊的價值...但這段代碼似乎不起作用,但螢火蟲也不會觸發控制檯中的任何錯誤。我究竟做錯了什麼?

$("a.buy").click(function(event) { 
event.preventDefault(); 
var msg = $(this).attr('rel'); 
alert(msg); 

}); 

更新:我糾正了HTML錯誤,我有。它不防止違約。而點擊事件似乎不起作用。

添加所有其他腳本工作的代碼頂部。

+0

如果這不起作用,它*應該*,你可能在腳本的其他地方有錯誤。將你的jQuery粘貼到[JS Lint](http://jslint.com/)中,看看它是否會拋出任何錯誤;未終止的字符串,語法錯誤等。如果沒有錯誤,請檢查干擾您的點擊處理程序的其他功能/處理程序。 –

回答

1

據在這裏工作精細http://jsfiddle.net/niklasvh/NFfe5/但要注意,你必須在你的HTML錯誤,你缺少周圍href=#"

引號確保你的代碼被包裝在一個DOM準備,以及:

$(function(){ 
// your code 
}); 
+0

糾正了錯誤..但不工作。 – esafwan

+1

@esagwan問題在其他地方。請分享您的其他代碼,或者鏈接到您的頁面。 – Niklas

+0

在所有其他工作的腳本的頂部添加。 – esafwan

0

this在這種情況下綁定到全局對象。我相信event.target將是您想要的DOM對象。

$("a.buy").click(function(event) { 
event.preventDefault(); 
//here, this refers to the global object, not the a element 
//unless jquery is doing some magic to bind it 
//event.target at this point in execution should be the a element 
var msg = $(this).attr('rel'); 
alert(msg); 

}); 
+0

我不明白 – esafwan

0

試試這個

$(document).ready(function(){ 

     $("a.buy").live('click',function(event) { 
      event.preventDefault(); 
      var msg = $(this).attr('rel'); 
      alert(msg); 

     }); 
}); 
0

我已經測試,寫入沒有問題。代碼如下:

<a href="#" class="buy" rel="WVSEU1Y">buy</a> 
<script type="text/javascript"> 
    $(function() { 
     $(".buy").bind("click", function() { 
      alert($(this).attr("rel")); 
     }); 
    }) 
</script>