Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery adding an onclick event to a href link

i am converting over from websforms to asp.net mvc and i have a question.

i have a loop that generates links dynamicallly where picNumberLink is a variable in a loop and image is a variable image link.

i want to avoid putting javascript actions inline so in my webforms project is did the following:

hyperLink.Attributes.Add("onclick", "javascript:void(viewer.show(" + picNumberlink + "))");

what is the equivalent using jquery in asp.net mvc?

I have seen examples of using the $(document).ready event to attach on clicks but i can't figure out the syntax to pass in the picNumberLink variable into the javascript function.

suggestions?

like image 418
leora Avatar asked Aug 13 '09 10:08

leora


3 Answers

EDIT: If you generate your links with the ID of this form:

<a id="piclink_1" class="picLinks">...</a>
<a id="picLink_2" class="picLinks">...</a>

<script type="text/javascript">
    $('a.picLinks').click(function () {
        //split at the '_' and take the second offset
        var picNumber = $(this).attr('id').split('_')[1];
        viewer.show(picNumber);
    });
</script>
like image 54
karim79 Avatar answered Sep 21 '22 12:09

karim79


var functionIWantToCall = function(){
    var wrappedLink = $(this);
    //some serious action
}

//this should be called on document ready
$("#myLinkId").click(functionIWantToCall);  

If you need to get URL of picture, keep it in anchor`s href:

var functionIWantToCall = function(event){
    event.preventDefault(); //this one is important
    var link = $(this).attr('href');
    //some serious action
}
like image 35
Arnis Lapsa Avatar answered Sep 20 '22 12:09

Arnis Lapsa


$(document).ready(function()
{

$('#LinkID').click(function() {
    viewer.show($(this).attr('picNumber'));
});

});

You can add an attribute called picNumber to your hyperlink tag and set this is your mvc view

The link in your view might look something like this:

<%= Html.ActionLink("Index", new { id = "LINKID", picNumber = 1 }) %>
like image 34
Rigobert Song Avatar answered Sep 22 '22 12:09

Rigobert Song