开发者

how to use one method for all clickable items using jquery?

开发者 https://www.devze.com 2023-03-08 12:10 出处:网络
What would be the best way to make the following jquery script into a single method which can be resued with all of my clickable spans? As you can see each click event is doing almost the exact same t

What would be the best way to make the following jquery script into a single method which can be resued with all of my clickable spans? As you can see each click event is doing almost the exact same thing except for the specific CSS class and the spans unique ID. I have thought about using the jquery .children() method but I'm not sure how to assign the specific class to each span. Any help would be appreciated.

 
<p class="clickHolder">
    <span id="click1">Select Step 1</span> 
    <span id="click2">Select Step 2</span> 
    <span id="click3">Select Step 3</span> 
    <span id="cl开发者_运维知识库ick4">Select Step 4</span> 
    <span id="click5">Select Step 5</span>
</p>
<script type="text/javascript">
    $(document).ready(function () {
        $("#click1").click(function () {
            $("#wizardSteps").removeClass();
            $("#wizardSteps").addClass("step1");
        });

        $("#click2").click(function () {
            $("#wizardSteps").removeClass();
            $("#wizardSteps").addClass("step2");
        });

        $("#click3").click(function () {
            $("#wizardSteps").removeClass();
            $("#wizardSteps").addClass("step3");
        });

        $("#click4").click(function () {
            $("#wizardSteps").removeClass();
            $("#wizardSteps").addClass("step4");
        });

        $("#click5").click(function () {
            $("#wizardSteps").removeClass();
            $("#wizardSteps").addClass("step5");
        });

    });
</script>


This should work:

$('[id^="click"]').click(function () {
    var stepnum = $(this).attr('id').substr(5);
    $("#wizardSteps").removeClass();
    $("#wizardSteps").addClass("step" + stepnum);
});


Like this:

<p class="clickHolder">
    <span class="clickable" id="click1">Select Step 1</span> 
    <span class="clickable" id="click2">Select Step 2</span> 
    <span class="clickable" id="click3">Select Step 3</span> 
    <span class="clickable" id="click4">Select Step 4</span> 
    <span class="clickable" id="click5">Select Step 5</span>
</p>

<script type="text/javascript">
    $(document).ready(function () {
        $(".clickable").click(function () {
            $("#wizardSteps").removeClass();
            $("#wizardSteps").addClass( /* calculate step */);
        });
    });
</script>
0

精彩评论

暂无评论...
验证码 换一张
取 消