2015-08-14 185 views
0

我正在創建一個Web應用程序,用戶在其中添加一個選項卡並放置其內容。這個標籤是動態創建的。我在谷歌搜索它,並試圖給出的解決方案,但沒有一個爲我工作。所以我在這裏發佈了一個問題。顯示動態添加選項卡jquery選項卡

我的代碼是:

<div id="tabs" class="htabs"> 
    <a href="#tab-general"><?php echo $tab_general; ?></a> 
    <a onclick="addtab();" id="add-tab"><?php echo $add_tab; ?></a> 
</div> 

和文字是: -

<script type="text/javascript"> 

$('#tabs a').tabs(); 

var tab_count = '<?php echo $tab_count; ?>'; 

function addtab(){ 

    var html = ''; 

    $('#add-tab').before('<a href="#product-tab-'+tab_count+'" class="nearest">Tab '+tab_count+'</a>'); 

    html += '<div id="product-tab-'+tab_count+'" class="nthDiv">'; 
    html += '<table class="form">' 
    html += '<tr>'; 

    html += '<td>'; 
    html += 'Name'+tab_count;  
    html += '</td>'; 

    html += '<td>'; 
    html += '<input type="text">'; 
    html += '</td>'; 

    html += '</tr>'; 
    html += '</table>'; 

    html += '</div>'; 

    $('#form').append(html); 
    $('#tabs a').tabs("refresh"); 

    //$('#tabs a').tabs("option", "selected", -1); tried but doesn't work 

    //$('#tabs a').tabs("option", "active", -1); tried but doesn't work 


    tab_count++; 

} 

</script> 

我的jQuery的版本是jquery-1.7.1.min.js和jQuery UI的版本爲1.8

問題是新標籤沒有被激活/選中。我必須手動點擊該選項卡才能激活它。

回答

0

您的標籤標記是錯誤的

$('#tabs').tabs({ 
 
    beforeActivate: function(e, ui) { 
 
    return ui.newTab.find('#add-tab').length == 0; 
 
    } 
 
}); 
 

 
var tab_count = 1; 
 

 
$('#add-tab').click(function() { 
 

 
    var html = ''; 
 

 
    $('#add-tab').parent().before('<li><a href="#product-tab-' + tab_count + '" class="nearest">Tab ' + tab_count + '</a></li>'); 
 

 
    html += '<div id="product-tab-' + tab_count + '" class="nthDiv">'; 
 
    html += '<table class="form">' 
 
    html += '<tr>'; 
 

 
    html += '<td>'; 
 
    html += 'Name' + tab_count; 
 
    html += '</td>'; 
 

 
    html += '<td>'; 
 
    html += '<input type="text">'; 
 
    html += '</td>'; 
 

 
    html += '</tr>'; 
 
    html += '</table>'; 
 

 
    html += '</div>'; 
 

 
    $('#tabs').append(html); 
 
    $('#tabs').tabs("refresh").tabs("option", "active", -2); 
 

 

 
    tab_count++; 
 

 
})
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.js"></script> 
 
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/redmond/jquery-ui.css"/> 
 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.js"></script> 
 

 
<div id="tabs" class="htabs"> 
 
    <ul> 
 
    <li><a href="#tab-general">Gen</a></li> 
 
    <li><a href="#" id="add-tab">Add</a></li> 
 
    </ul> 
 
    <div id="tab-general"> 
 
    tab-general 
 
    </div> 
 

 
</div>

+0

如果我使用'$( '#標籤')。標籤()'那麼它不會產生任何標籤。相反,'tab' div內的所有標籤都是不可見的。所以我必須使用'$('#tabs a')。tabs' –

+0

並且刷新選項卡給我錯誤$(...)。tabs(...)是未定義的。我使用了'$('#tabs a')。tabs(「refresh」)。tabs(「option」,「active」,-2);' –

+0

@VedPandya你的html是錯誤的...看到上面的標記 –