对于影响其他div的菜单链接的每个循环

时间:2018-02-01 21:13:22

标签: javascript jquery

我正在尝试了解如何将此代码转换为循环,因此我不必在将来每次$('.popup-[insert nr]').click复制一个新的菜单链接以进行导航。 此代码的目的是:单击链接,切换或向隐藏的div添加一个节目类,如果点击任何其他链接,则会隐藏每个显示的div。

var popContent = $('.popup-1-content');
var popContent2 = $('.popup-2-content');
var popContent3 = $('.popup-3-content');
var popContent4 = $('.popup-4-content');

var popupArray = [popContent, popContent2, popContent3, popContent4];

$('.popup-1').click(function () {

    if ( popContent.hasClass("show") ) {
        popContent.removeClass("show");
    } else {
        for (var i = 0; i < popupArray.length; i++) {
           popupArray[i].removeClass("show");
        }
        popContent.addClass("show");
    }
    return false;
});

$('.popup-2').click(function () {

    if (popContent2.hasClass("show") ) {
        popContent2.removeClass("show");
    } else {
        for (var i = 0; i < popupArray.length; i++) {
           popupArray[i].removeClass("show");
        }
        popContent2.addClass("show");
    }
    return false;
});


$('.close-popup a').click(function(){
$('.popup-content').toggleClass('hide').removeClass('show');
return false;
});

5 个答案:

答案 0 :(得分:1)

不看你的HTML结构很难,但想法是为每个链接创建一个循环,并用这样的索引变量替换数字:

$.each('a', function(i, link) {
    $('.popup-' + i).click(function () {

        $('div').removeClass("show");
        $(this).parent.addClass("show");

        return false;
    });
});

答案 1 :(得分:1)

更新

  

“...我尝试了你的代码,但它需要进行编辑,因此它不会将链接定位在链接下方,因为div位于页面的随机部分。”

更新的演示通过向每个链接添加data-*属性来解决之前提到的问题。点击链接后,会通过使用div.pop方法将data-idx.pop的索引位置相匹配,从而找到第n个.eq()。以下示例不起作用,它仅仅是相关部分,强调索引号以显示2个值之间的相关性。

<a href='#/' class='lnk' data-idx= '的 3 '>POP3</a>

$('.pop').eq( 3 ).addClass('show')

以下是没有额外实用程序或注释的核心代码,精简和链接。

$('.lnk').on('click', function() {
  var idx = $(this).data('idx');
  $('.pop').removeClass('show').eq(idx).addClass('show');
});

 <a href='#/' class='.lnk' data-idx='0'>POP0</a>

有关完整更新的代码,请参阅下面的演示。

在状态交替的任何自动或手动控制的元素组(例如滑块)上(例如hide和show),控制流的最简单方法是隐藏所有元素,然后显示当前活动的元素。 / p>

在演示中评论的详细信息

演示

/* This is just to space the links apart. Upadted to provide
|| random location for .lnk's
*/
$('a.lnk').each(function(idx, a) {
  var ran = getRandom(1, 60);
  a.style.top = (idx * ran) + 'px';
  a.style.left = (idx * ran) + 'px';
});

// Click any a.lnk...
$('a.lnk').on('click', function() {

  // Reference the div.pop the clicked link belongs to

  /* The next statement works if each popup was positioned after
  || a corresponding link. It is commented out in leiu of the 
  || uncommented statement that follows this statement.
  */ // var pop = $(this).next('div.pop');

  // Get the clicked link's data-idx number
  var idx = $(this).data('idx');

  // Gather all .pop
  var pop = $('.pop');

  // ALL .pop remove class .slow
  pop.removeClass('show');

  /* .pop will open. The specific .pop that corresponds with the
  || clicked link is determined by matching the .pop's current
  || indexed position with that of the indexed position of in     
  || $('.pop') by using the eq() method and passing data-idx
  */
  pop.eq(idx).addClass('show');

});

/* This function is not neccessary. Its purpose is to generate a
|| random number between min and max parameters (inclusive)
*/
function getRandom(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
a.lnk {
  display: inline-block;
  position: relative;
  z-index: 1;
  background:#000;
  color:gold;
  
}

.pop {
  display: none;
}

.pop.show {
  display: block;
  margin-top: 30px
}
<a href='#/' class='lnk' data-idx='0'>POP0</a>
<a href='#/' class='lnk' data-idx='1'>POP1</a>
<a href='#/' class='lnk' data-idx='2'>POP2</a>
<a href='#/' class='lnk' data-idx='3'>POP3</a>
<a href='#/' class='lnk' data-idx='4'>POP4</a>


<div class='pop'>
  <img src='https://i.imgur.com/ydfYXqh.jpg'>
  <header>POP0</header>
</div>


<div class='pop'>
  <img src='https://i.imgur.com/DrEwPH0.jpg'>
  <header>POP1</header>
</div>


<div class='pop'>
  <img src="https://i.imgur.com/AXUJEUS.jpg">
  <header>POP2</header>
</div>


<div class='pop'>
  <img src='https://i.imgur.com/MEPxbq4.jpg'>
  <header>POP3</header>
</div>


<div class='pop'>
  <img src='https://i.imgur.com/dp8G9Fr.jpg'>
  <header>POP4</header>
</div>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 2 :(得分:0)

使用更好的CSS选择器抓取所有弹出窗口。然后使用jquery&#39; s each在每个列表上附加一个点击处理程序来遍历列表。

您手动切换类,但JQuery内置了toggleClass。请改用它。在你的情况下,你声明你想要在一个弹出窗口改变它之后从所有其他元素中删除该类,为此我们可以使用jquery&#39; .not方法指定获取除项目之外的所有项目指定,然后我们只使用removeClass从这些元素中删除类。

var popups = $('[class$="-content"]').filter('[class^="popup-"]');

popups.each(function(index, popup) {
  $(".popup-" + (index + 1)).click(function(e) {
    $(popup).toggleClass("show");
    popups.not(popup).removeClass("show");
  });
});

&#13;
&#13;
var popups = $('[class$="-content"]').filter('[class^="popup-"]');

popups.each(function(index, popup) {
  $(".popup-" + (index + 1)).click(function(e) {
    $(popup).toggleClass("show");
    popups.not(popup).removeClass("show");
  });
});
&#13;
.show {
  color: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="popup-1">toggle 1</button>
<button class="popup-2">toggle 2</button>
<button class="popup-3">toggle 3</button>
<button class="popup-4">toggle 4</button>

<div class="popup-1-content">1</div>
<div class="popup-2-content">2</div>
<div class="popup-3-content">3</div>
<div class="popup-4-content">4</div>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

添加一个公共类。

<!-- Added a common class popup-content -->
<div class=".popup-1-content popup-content">...<div>

在添加事件处理程序时选择公共类,请参考$(this),假设您正在使用jQuery,以获取事件发生的实例(单击特定元素),这也可以使用event.target捕获vanilla js在将其传递给处理事件的回调函数时。

ex jQuery:

$('.popup-content').on('click', function(){
    // Check if already open, early exit
    if ($(this).hasClass('show')) return;
    // Close them all
    $('.popup-content').removeClass('show')
    // Open the one being clicked
    $(this).addClass('show');
})

另一种选择是使用通配符选择器

$('[class^="popup"]').on('click', function(){
    // Check if already open, early exit
    if ($(this).hasClass('show')) return;
    // Close them all
    $('[class^="popup"]').removeClass('show');
    // Open the one being clicked
    $(this).addClass('show');
})
p {
  display: none;
  border: solid 1px black;
}

.show p {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="popup-content-1">
  1
<p>hidden content 1</p>
</div>
<div class="popup-content">
  2
<p>hidden content 2</p>
</div>

答案 4 :(得分:0)

使用选择器属性(以...开头),您可以选择所有弹出窗口,并根据弹出类名称隐藏或显示其内容。这样您就可以添加任意数量的弹出窗口。

<button class="popup-1">1</button>
<span class="content-popup-1">First</span>

$("[class^=popup]").click(function() {
    $(".content-" + this.className).toggleClass('hide');
});

这里的工作示例:https://jsfiddle.net/e9qep53w/

此处有关于查询选择器的更多信息https://api.jquery.com/category/selectors/