可重用的jQuery函数

时间:2019-04-12 20:21:59

标签: javascript jquery

        <div class="row">
            <div class="col my-col my-col-blue" id="show1">
                <h3>something</h3>
                <p>Lorem error ullam?</p>
            </div>
            <div class="col my-col my-col-red" id="show2>
                <h3>something</h3>
                <p>Lorem error ullam?</p>
            </div>
            <div class`enter code here`="col my-col my_nav" id="show3">
                <h3>something</h3>
                <p>Lorem error ullam?</p>
            </div>
        </div>
        <div class="row" id="target1" style="display: none">
            <div class="menu col my-col my-col-blue">fist 1</div>
        </div>
        <div class="row" id="target2" style="display: none">
            <div class="col my-col my-col-red">fist 2</div>
        </div>
        <div class="row" id="target3" style="display: none">
            <div class="col my-col my_nav">fist 3</div>
        </div>

当单击id(show1)以便切换(target1)时,如何获取正确的ID。我能够做到如下,它可以工作,但是我想创建一个可重用的函数。我可以按照自己的方式做,但是我需要3种不同的功能。谢谢

ps。单击id(show1)时,id(target1)切换(显示)。

$(document).ready(function() {
      $("#show1").click(function() {
           $("#target1").toggle();
      })
 })

1 个答案:

答案 0 :(得分:3)

我更新了您的IDS,为每个标题提供了一个类,并使用了数据目标来使其起作用。

$(document).ready(function() {
      $(".nav-link").on("click",function() {
           $($(this).data("target")).toggle();
      })
 })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
            <div data-target="#target1" class="col my-col my-col-blue nav-link" id="show1">
                <h3>something</h3>
                <p>Lorem error ullam?</p>
            </div>
            <div data-target="#target2" class="col my-col my-col-red nav-link" id="show2">
                <h3>something</h3>
                <p>Lorem error ullam?</p>
            </div>
            <div data-target="#target3" class="col my-col my_nav nav-link" id="show3">
                <h3>something</h3>
                <p>Lorem error ullam?</p>
            </div>
        </div>
        <div class="row" id="target1" style="display: none">
            <div class="menu col my-col my-col-blue">fist 1</div>
        </div>
        <div class="row" id="target2" style="display: none">
            <div class="col my-col my-col-red">fist 2</div>
        </div>
        <div class="row" id="target3" style="display: none">
            <div class="col my-col my_nav">fist 3</div>
        </div>