How to add the id to dynamically created jquery ta

2019-03-05 18:50发布

问题:

I am creating dynamically jQuery tabs. I want to assign the id to each tab.

$("#addTab").live('click', function() {
    index++;
    var title = 'Tab.....  ' + index;
    var url = '#fragment-' + index;

    addTab(url, title, index);
    $('li[class=ui-state-default]').id(this)=1; // this line to add id

});

but id is not assigning to the tab..

JS Fiddle

回答1:

$('li.ui-state-default:last').attr('id', 'some_' + index); // only Numeric id not allowed

DEMO

NOTE: $('li.ui-state-default').attr('id', 'some_' + index); was change all li's id have class ui-state-default, but current code will only change the last one's id.



回答2:

 $('li[class=ui-state-default]').id(this)=1

should become

 $('YOUR_NEW_TAB_SELECTOR').attr('id',1)

You use .attr method to set the attribute "id" to "1".



回答3:

Hiya demo :) http://jsfiddle.net/gP3YZ/7/

code

$(document).ready(function() {
    $("#tabs").tabs({
        tabTemplate: "<li><a href='#{href}'>#{label}</a> <p title='close' id='removeTab' style='cursor:pointer;display:inline'>x</p></li>"
    });
});

$(function() {
    var index = 0;
    $("#addTab").live('click', function() {
        index++;
        var title = 'Tab.....  ' + index;
        var url = '#fragment-' + index;

        addTab(url, title, index);
        $('li.ui-state-default').attr("id","1");
        alert($('li.ui-state-default').attr("id"));

    });

    function addTab(url, title, index) {

        $('#tabs').tabs("add", url, title, [index]);
    }
    $('#removeTab').live('click', function() {
    selected = $('p[id=removeTab]').index(this); // this line to add id
      $('#tabs').tabs("remove", [selected]);

    });


     $('#appendText').live('click', function() {
        $('#tabs .ui-tabs-panel').each(function(index) {

             if(!($(this).hasClass('ui-tabs-hide'))){
                 //do the dew!
                 $(this).append("Bla Bla!!!");

             }
        });
    });


});



​