tags:

views:

60

answers:

2

Does anyone know how can I assigned onclick for a tag with jquery

Exmaple:

<a id="abc">abc</a>

I want to assign onclick="test()" in the above a tag by jquery, anyone know how to do it?

+4  A: 
$(document).ready(function(){ // all jQuery code should run from this event
    $('div').click(function(){
        // find the div that was clicked on:
        $(this).css('color', 'red');
    }); //click
}); //doc.ready

Source: http://docs.jquery.com/Events/click

For your update request, as ecounysis said, you can bind the function, bu make sure it returns false, to prevent the real link from working (if you have a href):

function test(){
  alert("Hello");
  return false;
}

$(function(){
  $('#abc').click(test);
});

if you can't change test, you can also do:

$('#abc').click(function(){
      test();
      return false;
});

Example: http://jsbin.com/aseku

Kobi
+2  A: 
$(function() { 
    $("#abc").click(test);
});
ecounysis
Nope, should be `.click(test);` - or you start the function instead on binding it. Unless somehow `test()` returns a function, of course...
Kobi
Good point. I have edited my response based on your comment.
ecounysis