选项卡小部件难度 - 所有选项卡中的新选项卡Div文本显示

时间:2014-06-02 18:02:21

标签: jquery html jquery-ui tabs

我刚学会了Tabs Widget,并制作了一个快速代码块,在单击“添加标签”按钮时添加了一个标签,并在单击“删除标签”按钮时删除标签。我用“Projquery”这本书作为参考。不幸的是,每当点击“添加标签”按钮而不是仅添加一个包含内容的标签时,它也会将新标签的内容添加到所有前面的标签中。我已经检查了12次语法,但无济于事。肯定会得到答案:)

问题 - 按钮添加包含内容的新选项卡,以及将文本添加到旧选项卡,它不应该

  <script type="text/javascript">
  $(document).ready(function(){
   $("#tabs").tabs();

   $("button").button().click(function(e){
    var tabsElem = $("#tabs");
    if(this.id == "add"){
       var tabID = tabsElem.children("div").length + 1;
       tabsElem.children("ul").append($("<li>").append($("<a>")
        .attr("href","#Tab " + tabID).text("Tab " + tabID)));
        $("<div>").attr("id","Tab" + tabID).text("Cotent for given tab number " 
            + tabID +", and BAM").appendTo(tabsElem);
    }else{
        tabsElem.children("div").first().remove();
        tabsElem.find("li").first().remove();
    }
    tabsElem.tabs("refresh");

   });
})
</script>
<body>
<div id = "tabs">
  <ul>
     <li><a href="#Tab1">Tab 1</a></li>
     <li><a href="#Tab2">Tab 2</a></li>
     <li><a href="#Tab3">Tab 3</a></li>
  </ul>
  <div id ="Tab1">Mad Content Don'tcha Y'know</div>
  <div id = "Tab2">Welcome to the free world, you hear</div>
  <div id = "Tab3">Last Time For Now</div>
</div>
<br />
<div id = "button" class = "ui-widget">
  <button id = "add">Add Tab!!!</button>
  <button id = "remove">Remove Tab!!!</button>
</div>
</body>
</html>

注意 - 为了简洁起见,我用jquery / css链接遗漏了head标签

1 个答案:

答案 0 :(得分:1)

也许你需要检查面包师十几次的语法;)

问题是您对anchor href属性的设置:

.attr("href","#Tab " + tabID)

注意“#Tab”和你连接的'tabID'之间的空格;导致href属性为“Tab 4”,“Tab 5”等。问题是你新创建的DIV没有所说的空间(也是好事 - 空间不是每个ID中的有效字符HTML spec):

$("<div>").attr("id","Tab" + tabID)

我确认修复附加锚点上“href”的设置可解决此问题:http://jsfiddle.net/2bxJ6/1/

相关问题