Jquery Tab添加删除

Tab 1 does not work. Tab 1 is drawn from MySQL table. I want show default tab and add or delete an extra tab and post mysql get inserted tab id append not count?. Can you help?

Visit jsfiddle jsfiddle.net/datakolay/33aM3/

Html

 <ul id="tabul">
  <li id="litab" class="ntabs add"><a href="" id="addtab">+</a></li>
   <li id="t21" class="ntabs"> Tab Mysql id 21
    <a href="" id="close21" class="close">&times;</a>
  </li>
   <li id="t22" class="ntabs"> Tab Mysql id 22
    <a href="" id="close22" class="close">&times;</a>
   </li>  
</ul>
<div id="tabcontent">
  <p id="c21">Test</p>    
  <p id="c22">Test</p> 
</div>

Javascript

$(function() {
var total_tabs = 0;
total_tabs++;
$("#addtab, #litab").click(function() {
    total_tabs++;
    $("#tabcontent p").hide();
    addtab(total_tabs);
    return false;
});
function addtab(count) {
    var closetab = '<a href="" id="close'+count+'" class="close">&times;</a>';
    $("#tabul").append('<li id="t'+count+'" class="ntabs">Tab Extra &nbsp;&nbsp;'+closetab+'</li>');
    $("#tabcontent").append('<p id="c'+count+'">Tab Content </p>');

    $("#tabul li").removeClass("ctab");
    $("#t"+count).addClass("ctab");

    $("#t"+count).bind("click", function() {
        $("#tabul li").removeClass("ctab");
        $("#t"+count).addClass("ctab");
        $("#tabcontent p").hide();
        $("#c"+count).fadeIn('slow');
    });

    $("#close"+count).bind("click", function() {
        // activate the previous tab
        $("#tabul li").removeClass("ctab");
        $("#tabcontent p").hide();
        $(this).parent().prev().addClass("ctab");
        $("#c"+count).prev().fadeIn('slow');

        $(this).parent().remove();
        $("#c"+count).remove();
        return false;
    });
}
});

MY NEW EDİT Visit jsfiddle jsfiddle.net/datakolay/33aM3/8/

 $(function() {  
 $('#tabcontent p').hide().filter(':lt(1)').show();
    $("#tabul li").removeClass("ctab");
    $(".ntabs").filter(':lt(1)').addClass("ctab");

    $("#addtab").click(function() {
     $("#tabcontent p").hide();
      var dataString = '';
             $.ajax({
              type: "POST",
              url: "add_tab.php",
              data: dataString,
              cache: false,
              success: function(html)
                 {
                  $("#tabul li").removeClass("ctab");
                  $("#t"+count).addClass("ctab");
                  $("#tabcontent p").hide();
                  $("#c"+count).fadeIn('slow');
                 }
              });              
          return false;
    });


    $(".ntabs").bind("click", function() {
      var id = $(this).attr('id')
      $("#tabul li").removeClass("ctab");
      $(".ntabs").addClass("ctab");

        $("#tabul li").removeClass("ctab");
        $("#"+id).addClass("ctab");
        $("#tabcontent p").hide();
        $("#c"+id).fadeIn('fast'); 
    });

    $(".close").bind("click", function() {
        var id = $(this).attr('id')
        $("#tabul li").removeClass("ctab");
        $("#tabcontent p").hide();
        $(this).parent().prev().addClass("ctab");
        $("#c"+id).prev().fadeIn('fast');
        $(this).parent().remove();
        $("#c"+id).remove();
        return false;
    });

You're only adding the event listener to dynamically added tabs i.e.; tab 2, tab 3, tab 4... since tab 1 is hardcoded into the html opposed to being dynamically loaded in, it's never getting the listener added. Although there are a ton of optimizations I'd add to this, the quick fix is to add.

 $("#t1").bind("click", function() {
      $("#tabul li").removeClass("ctab");
      $("#t1").addClass("ctab");
      $("#tabcontent p").hide();
      $("#c1").fadeIn('slow');
 });

I believe your problem is in fact in your HTML not your JQuery. It appears to work properly (as far as I can tell) if you modify your html from this:

<ul id="tabul">
    <li id="litab" class="ntabs add"><a href="" id="addtab">+</a>
        <li id="t1" class="ntabs"> Tab 1<a href="" id="close1" class="close">&times;</a></li>
    </li>
</ul>
<div id="tabcontent">
    <p id="c1">Test</p>    
</div>

To this:

<ul id="tabul">
    <li id="litab" class="ntabs add"><a href="" id="addtab">+</a></li>
</ul>
<div id="tabcontent">    
</div>

Then, I'd make a small adjustment to your JQuery, change: var total_tabs = 1; to: var total_tabs = 0;

Next, you'd need to work on the way your JQuery handles closing tabs. If the first tab is closed, the '+' tab is displayed. If a tab is closed that's not currently focused, it changes focus to the previous tab of the closed tab.

JSFiddle with my suggestions.

Edit: I also thought I'd present one more thing. My assumption is that you're going to have some way to dynamically add content to these tabs; given that, I'd dynamically add the first tab (like my suggestion would do) instead of hard coding it into the html simply due to the fact that your JQuery already works for tabs dynamically added (meaning you're doing something wrong with adding listeners to the static tab). Just my two cents.

Edit 2: To answer your question about how to access your MySQL data from JQuery, you should really google something like JQuery get data from MySQL database. That said, you've added PHP to the tags, so we'll assume that's what you want to use. You need to construct an AJAX call through JQuery to retrieve the information. Also, you need a PHP script to interact with the server.

PHP Script:

<?PHP
    $db_address = 'localhost';
    $db_user= 'root';
    $db_pass= 'password';
    $db_name= 'TabData';
    $db;
    function connect() {
    global $db, $db_server, $db_user, $db_password, $db_dbname;
        if (!$db) {
            $db = mysql_connect($db_server, $db_user, $db_password);
        }
        if (!$db) { 
            die('Could Not Connect: ' . mysql_error()); 
        } else {
            mysql_select_db($db_dbname);
        }
    }
    function disconnect() {
        global $db;
        if ($db) {
            mysql_close($db);
        }
    }
    function query($query) {
    global $db;
        if (!$db) {
            connect();
            if ($db) {
                return query($query);
            }
        } else {
            $result = mysql_query($query);
            return $result;
        }
    }
    function getTabData($id) {
        $result = query("SELECT * FROM tabs WHERE id = \"".$id."\"");
    }

    $data = array();
    $json = file_get_contents('php://input'); // read JSON from raw POST data

    if (!empty($json)) {
    $data = json_decode($json, true); // decode
    if(isset($data["id"]) && !empty($data["id"])) {
        connect();
        getTabData($data["id"]);
        disconnect();
    }
?>

Basically, that code will connect to a database named TabData and return in JSON the information from the row in table tabs with an ID matching that passed in the AJAX query.

JQuery for creating an AJAX call to the above PHP code (contained in a file named myPHP.php):

function updateTab(tabID) {
    $.ajax({
        type: "POST",
        url: "/myPHP.php",
        contentType: "application/json",
        data: JSON.stringify({id: tabID}),
        success: function (data) {
            var tabData = $.parseJSON(data);
            $.each($.parseJSON(data), function() {
                $("#c" + this.id).html("" + this.info);
            });
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("Error: " + "
XMLHttpRequest status: " + XMLHttpRequest.status + "
XMLHttpRequest statusText: " + XMLHttpRequest.statusText + "
textStatus: " + textStatus + "
errorThrown: " + errorThrown);
        }
    });
}

Basically, that code will connect to a php script named myPHP.php and send an AJAX query with the ID of the passed in ID. Upon successful return of the request, the success function will return, which parses the returned data from the PHP script and updated the content page of the appropriate id. I haven't tested this code (since I don't have a readily available environment); but it is code that I have slightly modified from some of my existing code (thus, it should work without too many adjustments).