jquery conflict with identical scripts

后端 未结 1 1162
攒了一身酷
攒了一身酷 2021-01-27 17:05

I am using jquery to load content into tabs, and switch the tabs on click. My problem is that one one page I am using this \"tab switcher\" twice, and it is causing a conflict.

相关标签:
1条回答
  • 2021-01-27 18:04

    I know that script - I actually refactored it for another question. The code is pretty bad, in the sense that it contains many bad practices. Let's see what can be done here:

    $(".tabs_content").not(':first-child').hide();
    var tabs = $('.tabs li');
    
    tabs.filter(':first-child').addClass('active');
    
    tabs.click(function() {
        var current = $(this);
    
        if(!current.hasClass('active')){
            current.addClass('active').siblings().removeClass('active');
            var activeTab = current.find("a").attr("href");
            current.parent().next().children().hide().filter(activeTab).fadeIn();
        }
    
        return false;
    });
    

    There - a single script for all your tabs. Rename all your tab containers to tabs. This uses some pretty heavy chaining, which really isn't very efficient, but given the DOM here there isn't much to do. Use this so you won't need two scripts that do essentially the same thing.

    See it working here: http://jsfiddle.net/E3SFt/2/. I copied your HTML character for character for this, with the minor modification to the class names as noted above. Also note that you've got some invalid HTML in there - li elements inside divs is not valid.

    Edit: Stupid mistake, this.hasClass should be current.hasClass

    0 讨论(0)
提交回复
热议问题