【问题标题】:How to add the id to dynamically created jquery tab如何将 id 添加到动态创建的 jquery 选项卡
【发布时间】:2012-05-17 08:23:10
【问题描述】:
我正在创建动态 jQuery 选项卡。我想将 id 分配给每个选项卡。
$("#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
});
但 id 没有分配给选项卡..
JS Fiddle
【问题讨论】:
标签:
jquery
jquery-ui
tabs
jquery-ui-tabs
jquery-tabs
【解决方案1】:
$('li[class=ui-state-default]').id(this)=1
应该变成
$('YOUR_NEW_TAB_SELECTOR').attr('id',1)
您使用 .attr 方法将属性“id”设置为“1”。
【解决方案2】:
$('li.ui-state-default:last').attr('id', 'some_' + index); // only Numeric id not allowed
DEMO
注意: $('li.ui-state-default').attr('id', 'some_' + index); 将所有 li 的 id 更改为 ui-state-default,但当前代码只会更改最后一个的 id。
【解决方案3】:
嗨演示 :) http://jsfiddle.net/gP3YZ/7/
代码
$(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!!!");
}
});
});
});