Combine jQuery .add Class () on the button, click only the item in w...

I am trying to combine multiple click functions with toggle class into one that will affect multiple elements separately. As seen on image i want to change css of element on click only for one which is inside same parent element as button ignoring any other elements with same class.

HTML:

<div style="display: inline-block">
    <section class="container2">
       1
    </section>
    <section>
        <p><button id="button">change</button></p>
    </section>
</div>

CSS:

.background {
    background: red !important;
}
.container2 {
    background: black;
    width: 100px;
    height: 50px;
    color: white;
}

jQuery:

var removeClass = true;

$("#button").click(function () {
    $('.container2').toggleClass('background');
    removeClass = false;
});

$(".container2").click(function() {
    removeClass = false;
});

$("html").click(function () {
    if (removeClass) {
        $(".container2").removeClass('background');
    }
    removeClass = true;
});

http://jsfiddle.net/dkhhecf2/1/

I know i can write something like this

$("#one, #two, #three").click...

But is there any other way?

http://i.stack.imgur.com/wJhKu.png

Any help would be greatly appreciated.

HTML

<div class="inline actionset">
   <div>1</div>
    <button>change</button>
</div>
<div class="inline actionset">
    <div>2</div>
    <button>change</button>
</div>

CSS

.inline {
    display:inline-block;
}
.highlight {
    background: red !important;
}
.actionset > div {
    background: black;
    width: 100px;
    height: 50px;
    color: white;
}

JS

$('.actionset button').on('click', function (e) {
    var $this = $(this);
    var el = $this.prev();
    el.toggleClass('highlight');
});

http://jsfiddle.net/dkhhecf2/2/

  1. An ID can only be used once per page
  2. Your markup needed some help to clean it up

As for the JS, you have a reference to the element being clicked $(this). Using this you can traverse the DOM using jQuery to select the element you want to affect. I used prev(); .

我来评几句
登录后评论

已发表评论数()

相关站点

+订阅
热门文章