用jquery Show(),hide()和toggle()来挣扎

时间:2014-10-05 21:04:31

标签: jquery

正在构建一些我可以使用一些帮助的功能/网站。我得到它的工作方式我需要它,但我认为这是非常粗糙所以任何帮助使它更清洁是值得赞赏的。

这是HTML。

     <div class="large-5 columns">
          <div id="t1" class="t1">
            <h3>
              <a href="#">
                Link one
              </a>
            </h3>
            <p id="r1">
              Panel 1. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
            </p>
          </div>
 <div id="t2" class="t2">
            <h3>
              <a href="#">
                Link two
              </a>
            </h3>
            <p id="r2">
              Panel 2. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
            </p>
          </div>
        </div> <div id="imageone" style="display:none">

标签中的第一张图片

以下是Jquery: 我会有更多标签,但现在就保持这样。

 <script>
$( "#t1 a" ).click(function() {
$( "#r1" ).toggle()
$( "#r2" ).hide()
$( "#imageone" ).show()
});


</script>

这是一个JSFIDDLE,它的工作原理我需要它才能工作,但我觉得它在我的Javascript方面真的很粗糙,任何人都可以帮我重写这个更简单的代码吗? http://jsfiddle.net/2jbf9cx0/

2 个答案:

答案 0 :(得分:0)

当你有类似的物品时,你永远不需要硬连线到ids。使用类和层次结构来使用可以找到匹配元素的单个处理程序。

JSFiddle:http://jsfiddle.net/2jbf9cx0/4/

带注释的代码:

  // Initial hide of all .info paragraphs
  $(".info").hide()

  // If any anchor in a .tab is clicked
  $(".tab a").click(function () {
        // Find the closest ancestor .tab
        var $tab = $(this).closest('.tab');

        // then the .info in that .tab
        var $info = $tab.find('.info');

        // Hide all the other infos (not excludes the target one)
        $('.info').not($info).hide();

        // Toggle the specific info
        $info.toggle();

        // Use a the id of the tab to find a matching image with data-id attribute
        var $image = $('[data-id=' + $tab.attr('id') + ']');

        // Hide all but the selected image
        $('images').not($image).hide();

        // Show the selected image (or toggle if you prefer)
        $image.show();
  });

答案 1 :(得分:0)

您正在使用数据属性http://jsfiddle.net/2jbf9cx0/2/

    $(".mytabs p").hide()
        $('.t').on('click', function () {
            $('.t p, .timg').hide();
            $(this).find('p').show();
            $('.timg[data-tag=' + $(this).data("tag") + ']').show();
    });

检查小提琴上的html以获取对代码的其他修改:)