【问题标题】:Dynamically create button for each div with class name, and create show/hide on click function为每个具有类名的 div 动态创建按钮,并创建显示/隐藏单击功能
【发布时间】:2017-11-22 16:47:37
【问题描述】:

我正在尝试想出一个很好的解决方案来轻松添加菜单页面。 每个菜单页面都应该是一个带有“shTab”类的 div,以标识它是一个显示/隐藏元素,我还想给每个 div 一个唯一的名称,这样我就可以创建具有该名称的按钮作为文本。

我正在使用硬编码的 html 创建每个 div,我想要一个 jQuery 函数首先获取所有 div,然后将其放入我的数组选项卡中。

然后我想遍历 tabs 数组,并为每个 div 创建一个按钮,该按钮应附加到 buttonContainer 类,以便所有按钮都像普通菜单一样位于同一区域。

我还希望为每个创建的按钮创建一个单击功能,该功能将 .hide() 所有选项卡,最后 .show() 属于单击按钮的选项卡。

我试图让它在jsFiddle 中工作,但我在尝试迭代它们时遇到了我的 div 元素的问题(我认为这就是问题所在)。

html

<div class='buttonContainer'>

</div>
<div class='container'>
  <div class='shTab' name='home'>
    <p>Homepage! yay</p>
  </div>
  <div class='shTab' name='contact'>
    <p>Contact page! yay</p>
  </div>
  <div class='shTab' name='images'>
    <p>no images yet :(</p>
  </div>
</div>

javaScript

var tabs = [];

$(document).ready(function(){

  $('div.shTab').each(function(i, obj) {
        tabs.push(obj);
  });

  for (var div in tabs) {
    div.hide();
    $('.buttonContainer').append(
            $('<button/>', {
          text: div.name,
          click: function () {
            for (var div in tabs) {
              div.hide();
            }
            this.show();
          }
      })
    );
  }

});

我注意到我的 for 循环中的 'div' 对象不能作为 jQuery 对象工作,.hide()、.name .... 等不能按我的意图工作。

我做错了什么?

【问题讨论】:

  • 我创建了一个小提琴(jsfiddle.net/yxg3w9u8)......也许它会有所帮助。但请注意,我不喜欢查询,所以我只使用了 JavaScript。
  • 谢谢,我修改了你的代码,现在它几乎可以满足我的需求。 (jsfiddle.net/yxg3w9u8/2) 仍然更喜欢 jQuery 版本。但是……这总比没有好!谢谢^^

标签: javascript jquery html


【解决方案1】:

同样的事情,通过 jQuery 完成。 Here's the fiddle,如果你需要的话。

// Create the tabs collection...
var tabs = $('.shTab');
// create the buttons, based on the tabs themselves
for (var i = 0; i < tabs.length; i++) {
  // wrap the individual tab in the jQuery object.
  var tab = $(tabs[i]);
  // use the tab's name attribute for the button text.
  var btn = $('<button>').html(tab.attr("name"));
  // hide the current tab.
  tab.hide();
  // Add the button to the containing div.
  $('.buttonContainer').append(btn);
}
/*****
 * event listener for the click
 *   NOTE: Because I've added the buttons dynamically,
 *    I can't simply listen to them as a set. I can
 *    either re-create the listener with each button,
 *    or use EVENT DELEGATION!
 *****/
$(".buttonContainer").on("click", "button", function() {
  // use the index of the clicked button to index the
  //  appropriate tab.
  var buttonIndex = $(this).index();
  var tab = $(tabs[buttonIndex]);

  // Show the current tab...
  tab.show()
    // ... and hide all the siblings!
    .siblings().hide();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='buttonContainer'>

</div>
<div class='container'>
  <div class='shTab' name='home'>
    <p>Homepage! yay</p>
  </div>
  <div class='shTab' name='contact'>
    <p>Contact page! yay</p>
  </div>
  <div class='shTab' name='images'>
    <p>no images yet :(</p>
  </div>
</div>

【讨论】:

  • 嘿,谢谢!有趣的解决方案是这样创建的按钮单击操作!永远不会想到这一点,我也不知道 .siblings() 存在。然而,我自己也设法提出了一个解决方案,基于我自己的尝试和@christian 的普通 js 尝试。如果您可以争论我们的哪个解决方案是“最好的”,请告诉我!
  • 真的不知道这是否有“最佳”,这是个人喜好问题。我更喜欢使用单个 jQuery 对象(用于 tabs 变量),并根据需要拉出每个选项卡——但这种方法要求我每次提取它时都将它包装在一个 jQuery 对象中。另外,我不关心在多个地方有相同的监听器——你为每个按钮重新实例化它。相反,我只有一个听众。但同样,个人品味。
  • 是的,只是想知道这两种解决方案如何在性能方面竞争?我不确定拥有大量注册听众是否是不好的做法?
  • 您是否计划使用数十万个标签?如果是这样,那么是的,严重的性能受到打击。但它更多的是内存泄漏的可能性。通过拥有一个监听器,无论有多少可能的元素被监听,我的内存占用都非常小。
  • 好的,谢谢。这回答了我的担忧。我有 10-15 个,所以这将是最小的内存消耗
【解决方案2】:

我通过查看所有帮助找到了答案。非常感谢。

$(document).ready(function(){
  var tabs = [];

	$('div.shTab').each(function(i, obj) {
        tabs.push($(obj));
  });

  for (var i = 0; i < tabs.length; i++) {
  	tabs[i].hide();
    $('.buttonContainer').append(
		$('<button/>', {
          text: tabs[i].attr('name'),
          click: function (event) {
            for (var i = 0; i < tabs.length; i++) {
              tabs[i].hide();
              if(tabs[i].attr('name') === event.target.innerHTML){
                tabs[i].show();
              }
            }
          }
      })
    );
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='buttonContainer'>

</div>
<div class='container'>
  <div class='shTab' name='home'>
    <p>Homepage! yay</p>
  </div>
  <div class='shTab' name='contact'>
    <p>Contact page! yay</p>
  </div>
  <div class='shTab' name='images'>
    <p>no images yet :(</p>
  </div>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-09
    • 2016-03-01
    • 2021-06-14
    • 1970-01-01
    • 2016-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多