简体   繁体   English

如何将jQuery插件应用于同一页面上的多个div?

[英]How to apply jQuery plugin to multiple divs on same page?

I'm working on a jQuery plugin and I need it to work on multiple divs on one page. 我正在使用jQuery插件,我需要它在一页上的多个div上工作。 Basically, I have two menus and when a user clicks on one menu item the background color changes. 基本上,我有两个菜单,当用户单击一个菜单项时,背景颜色会改变。 Right now, the effect is being applied to both menus instead of individually. 目前,效果已应用到两个菜单,而不是单独应用。 For example, if I click on item one of menu one the background changes but if I click on item two of menu two, the background of item one menu one is removed while the background of item 2 menu 2 changes. 例如,如果我单击菜单一的第一项,则背景发生变化,但是如果我单击菜单二的第二项,则将删除项一菜单一的背景,而项目二菜单二的背景发生了变化。

I need for the menus to be completely separate from each other. 我需要菜单彼此完全分开。 Clicking on menu one should not change menu two. 单击菜单一不应更改菜单二。 Here is how the plugin is set up so far: 到目前为止,这是该插件的设置方式:

(function ($) {
    $.fn.selectBox = function () {
        function get() {
            $('.ms-section-select li').first().addClass('ms-checked');
        }

        function get() {
            $('.ms-section-select li').click(function () {
                $('.ms-section-select li').removeClass('ms-checked');
                $(this).addClass('ms-checked');
            });
        }
        return this.each(get);
    };
})(jQuery);

$('.one').selectBox();
$('.two').selectBox();

Here is a jsfiddle example with all of the code http://jsfiddle.net/977hv/ 这是一个jsfiddle示例,其中包含所有代码http://jsfiddle.net/977hv/

You can try to apply the change on only the siblings of the selected element Is this what you are trying to do? 您可以尝试仅将更改应用于所选元素的同级对象。这是您要尝试的操作吗? http://jsfiddle.net/977hv/8/ http://jsfiddle.net/977hv/8/

$(this).siblings('.ms-section-select li').removeClass('ms-checked');

To apply it to the first child 应用于第一个孩子

    $('.ms-section-select li:first-child').addClass('ms-checked');
function selectBox () { 

    $('.ms-section-select li').on('click', function(){
        $(this).siblings().removeClass('ms-checked');
        $(this).addClass('ms-checked');

    })
};

selectBox();

this should do the trick - check: http://jsfiddle.net/977hv/6/ 这应该可以解决问题-检查: http : //jsfiddle.net/977hv/6/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM