msfanboy
msfanboy

Reputation: 5291

bind the click event to all links in a div with a certain class name

The first parts of the jquery call inside the document.ready is pseudo code. How can I do the $('.mainLink').each().click() correctly so that all links with class name mainLinks inside the NavigationPanel are bound to the click event. Is it bad to not use an id for a link?

$(document).ready(function () {

        $('.mainLink').each().click(function (e) {
                e.preventDefault();                
                $.ajax({
                    url: this.href,
                    beforeSend: OnBegin,
                    complete: OnComplete,
                    success: function (html) {
                        $('#ContentPanel').html(html);
                    }
                });
            });
        });  

<div id="NavigationPanel">  

        @Html.ActionLink("1", "Index", "First", null, new { @class = "mainLink" })
        @Html.ActionLink("2", "Index", "Two", null, new { @class = "mainLink"  })
        @Html.ActionLink("3", "Index", "Three", null, new { @class = "mainLink" })    
    </div>

Upvotes: 1

Views: 5410

Answers (2)

Sampson
Sampson

Reputation: 268424

If you just want to bind to all .mainLink within #NavigationPanel, the following works:

$("#NavigationPanel").on("click", ".mainLink", function(e){
    e.preventDefault();                
    $.ajax({
        url: this.href,
        beforeSend: OnBegin,
        complete: OnComplete,
        success: function (html) {
            $('#ContentPanel').html(html);
        }
    });
});

Upvotes: 1

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79840

Just do $('.mainLink').click(function (e) { which should bind all links with class .mainLink

If you want all links inside div ID NavigationPanel then try below,

$('.mainLink', $('#NavigationPanel')).click(function (e) {

Upvotes: 3

Related Questions