简体   繁体   中英

I need to run a function when a jquery-ui tab is clicked, what have I done wrong?

I found the (modified) code below but the alert does not happen. Please help. I also do not understand why the onclick is on "a[name=tab]", why not on "tab1" or a[tab1]?

  <script>
     jQuery(document).ready(function($){
        $("a[name=tab]").click(function(e){
           if($(this).attr('id')=="tab1")
           {
              alert("1");
           }
           if($(this).attr('id')=="tab2")
           {
              alert("2");
           }
     });

    <div id="tabs">
        <ul>
            <li><a name="tab" id="tab1" href="#tabs-1">One</a></li>
           <li><a name="tab" id="tab2" href="#tabs-2">Two</a></li>
        </ul>
        <div id="tabs-1">
            <p>First tab.</p>
        </div>
        <div id="tabs-2">
            <p>Second tab.</p>
        </div>
    </div>

I found there is a function that is run on tab change but I do not know how to use it and cannot find where to put it in my code. I would like help on this too. Thank you.

         $("#tabs").tabs({
                alert(ui.index);
             select: function(event, ui) {
                alert(ui.index);
                return true;
             }
         });

Use the activate event or beforeActivate event .

$(document).ready(function () {
    $("#tabs").tabs({
        activate: function (event, ui) {
            alert(ui.index);
        }
    });
});

First , Why use a[name=tab] and not [tab1] ?

a[name=tab] means an a tag with a name attribute equal to tab .
If you use a[tab1] it means an a tag that has a tab1 attribute.

You should check the jquery docs about it.
http://api.jquery.com/category/selectors/attribute-selectors/

Second , your code isn't working because it has an error, but you can fix it like this:

 $("#tabs").tabs({
     select: function(event, ui) {
        alert(ui.index);
        return true;
     }
 });

By the way, you should check about jQuery UI tabs
http://api.jqueryui.com/tabs/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM