【问题标题】:Create new div-tabs with Javascript [without jQuery] [with jQuery already solved]使用 Javascript [无 jQuery] [已解决 jQuery] 创建新的 div-tabs
【发布时间】:2014-07-19 00:01:13
【问题描述】:

我有一个关于如何使用 JavaScript 创建 div 的大问题。在这种情况下,我有选项卡,我希望能够从左侧表格中获得的两个变量中创建一个新变量;一个是名称,另一个是内容。示例:http://s2.subirimagenes.com/imagen/previo/thump_8932774captura-de-pantalla.png

函数应该如何从两个变量中创建这个新选项卡?

这是选项卡的 HTML:

<div class="w3c">

     <div id="tab16">
         <a href="#tab16">Tab 16</a>
         <div>One might well argue, that...</div>
     </div>

     <div id="tab17">
         <a href="#tab17">Tab 17</a>
         <div>... 30 lines of CSS is rather a lot, and...</div>
     </div>

     <div id="tab18">
         <a href="#tab18">Tab 18</a>
         <div id="Prueba">... that 2 should have been enough, but...</div>
     </div>

</div>  

和 CSS:

.w3c { 
    min-height: 250px; 
    position: relative; 
    width: 100%; 
}

.w3c > div { 
   display: inline; 
}

.w3c > div > a { 
   margin-left: -1px; 
   position: relative; 
   left: 1px; 
   text-decoration: none; 
   color: black; 
   background: white; 
   display: block; 
   float: left; 
   padding: 5px 10px; 
   border: 1px solid #ccc; 
   border-bottom: 1px solid white; 
}

.w3c > div:not(:target) > a { 
   border-bottom: 0; 
   background: -moz-linear-gradient(top, white, #eee); 
}   

.w3c > div:target > a { 
   background: white; 
}   

.w3c > div > div { 
   background: white; 
   z-index: -2; 
   left: 0; 
   top: 30px; 
   bottom: 0; 
   right: 0; 
   padding: 20px; 
   border: 1px solid #ccc; 
}   

.w3c > div:not(:target) > div { 
   position: absolute 
}

.w3c > div:target > div { 
   position: absolute; 
   z-index: -1; 
}

【问题讨论】:

  • 是的 BenSorter,我可以。我怎样才能做到这一点?非常感谢
  • 不要忘记,如果你用js添加标签,你需要在添加标签后实例化标签。您还需要添加一个选项卡导航。请参阅 this 而不是 this
  • 非常感谢 BenSorter 和 Pete。
  • 没有 jQuery 有没有机会做到这一点?

标签: javascript html function tabs createelement


【解决方案1】:

首先,创建新元素:

Best way of creating a new element in jQuery

var $div = $("<div>", {id: "tabN"});

然后,添加内容:

$div.html("some content");

最后,append 新创建的元素出现在你需要的地方。

$(".w3c").append($div);

【讨论】:

    【解决方案2】:

    BenSorter's jQuery answer 的纯 JavaScript 版本:

    var div = document.createElement('div');
    div.id = "tabN";
    div.innerHTML = "some content";
    document.querySelector(".w3c").appendChild(div);
    

    文档:


    注意: 上面的无 jQuery 解决方案仅适用于相当“现代”的浏览器,这意味着只有 Internet Explorer 8 及以下版本不支持这些方法。在您需要支持非常旧的 IE 的可悲情况下,使用 jQuery 会容易得多。

    【讨论】:

      猜你喜欢
      • 2013-09-29
      • 1970-01-01
      • 2011-07-15
      • 1970-01-01
      • 2014-09-04
      • 1970-01-01
      • 1970-01-01
      • 2013-09-20
      • 2012-07-29
      相关资源
      最近更新 更多