get the value of rel attribut of a link on click event of link using jquery
I have many link like this with different rel attributes
<a href="#" class="buy" rel="WV开发者_如何学GoSEU1Y">buy</a>
I want to get the value of rel attribute on click... but this code doesn't seem to work but firebug also doesn't fire any error in console. What am i doing wrong?
$("a.buy").click(function(event) {
event.preventDefault();
var msg = $(this).attr('rel');
alert(msg);
});
update: I corrected the html error i had. Its not preventing default. And the click event doesnt seem to work.
Adding the code top of all the other scripts worked.
It is working fine here http://jsfiddle.net/niklasvh/NFfe5/ but note that you have an error in your HTML, you are missing the quotation mark around href=#"
Make sure your code is wrapped in a DOM ready as well:
$(function(){
// your code
});
try this
$(document).ready(function(){
$("a.buy").live('click',function(event) {
event.preventDefault();
var msg = $(this).attr('rel');
alert(msg);
});
});
this
is bound to the global object in this case. I believe that event.target
will be the DOM object you want.
$("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);
});
I have tested, the write is no problem. Code is as follows:
<a href="#" class="buy" rel="WVSEU1Y">buy</a>
<script type="text/javascript">
$(function () {
$(".buy").bind("click", function () {
alert($(this).attr("rel"));
});
})
</script>
精彩评论