如何在jquery中创建show / hide div的多个实例? [英] How to create multiple instances of show/hide div in jquery?

查看:96
本文介绍了如何在jquery中创建show / hide div的多个实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码

$(document).ready(function() {
  $('a#slick-toggle').click(function() {
 $('#slickbox0').toggle(400);
 return false;
  });
});


<a id="slick-toggle" href="#">Show/Hide</a>

<div id="slickbox" style="display: none;">
hidden content here
</div>

问题是,如果在html部分上有超过1个这样的实例,那么页面,它不会工作。我不是很擅长JS。 div id我要独特....但是如何让每个链接切换相应的框?

The problem is, if there is more than 1 instance of this on the html part of this on the page, it wont work. Im not very good at JS. The div id I gotta make unique.... but how do I make each link toggle the corresponding box?

推荐答案

你不应该不要在HTML中重复ID。但是你确实希望在jQuery中使用相同的功能,所以添加一个公共类名,以便你可以将函数应用于所有这些锚点。

You shouldn't repeat IDs in your HTML. But you do want to use the same functionality in jQuery, so add a common class name so that you can apply the function to all of these anchors.

此外,既然你'不确定HTML结构是否可预测,你需要在anchor元素和div元素之间输出一个链接。请注意下面的data-id属性:

Also, since you're not sure about whether the HTML structure can be predictable, you'll need to output a link between anchor element and div element. Note the data-id attribute below:

<a id="someID" class="slick-toggle" data-id="334" href="#">Show/Hide</a>

<div id="someOtherID" class="slickbox" data-id="334" style="display: none;">
  hidden content here
</div>

这个334可以是任何东西。这将是您可以在输出内容时决定的独特内容。

This "334" could be anything. This would be something unique that you can decide on when you're outputting the content.

现在您的代码可以定位每个.slick-toggle类,并让它切换到关联div。

Now your code can target each .slick-toggle class, and have it toggle the associated div.

$(document).ready(function() {
    $('a.slick-toggle').click(function() {
        var dataID = $(this).attr("data-id");
        $("div[data-id=" + dataID + "].slickbox").toggle(400);
        return false;
    });
});

这篇关于如何在jquery中创建show / hide div的多个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆