Jquery event fire with bootstrap tab

2019-09-11 11:23发布

问题:

I am using bootstrap tab in my view

    @Html.ValidationSummary(true)
        <ul id="MyTabs" class="nav nav-tabs nav-justified">
            <li class="active"><a data-toggle="tab" href="#details" id="TabDetailsLink">Personal
                Details</a></li>
            <li><a data-toggle="tab" href="#tab1" id="Tab1">T1</a></li>
            <li><a data-toggle="tab" href="#tab2" id="Tab2">T2</a></li>

        </ul>

and i use jquery for catch the event
$(".MyTabs li").click(function (e) {
    alert(2);
});  

My expectation is to get the alert whenever I change the tabs. But the event is not getting fired. Mine is an ASP.NET MVC 4 web api application.

回答1:

Your jQuery selector is wrong ! MyTabs is the Id. So use it with # prefix

This should work.

$("#MyTabs li").click(function (e) {
    e.prevelitDefault(); 
    alert(2);
});

Or you can use your existing jQuery selector if you add this class to yuur ul element.

<ul id="MyTabs" class="MyTabs nav nav-tabs nav-justified">

When using Id as your jQuery selector, use # prefix ( Ex : $("#myElementUniqueID"))

When using css class as your jQuery selector, use . prefix ( Ex : $(".myCssClss") )