javascript - Multiple select divs with CTRL pressed - Stack Overflow

I have 10 divs<div id="div_1" class="myDivs"><div><div id="di

I have 10 divs

<div id="div_1" class="myDivs"></div>
<div id="div_2" class="myDivs"></div>
<div id="div_3" class="myDivs"></div>
...

O want to select 5 of them with a click handler using jQuery.

$(".myDivs").on("click", function() {
    console.log('all clicked DIVs IDs...');
}

Is there a functionality to do this with jQuery? I would like to click them and get all IDs of the clicked divs. Thanks for your help!

I have 10 divs

<div id="div_1" class="myDivs"></div>
<div id="div_2" class="myDivs"></div>
<div id="div_3" class="myDivs"></div>
...

O want to select 5 of them with a click handler using jQuery.

$(".myDivs").on("click", function() {
    console.log('all clicked DIVs IDs...');
}

Is there a functionality to do this with jQuery? I would like to click them and get all IDs of the clicked divs. Thanks for your help!

Share Improve this question edited Feb 24, 2016 at 10:26 Rory McCrossan 338k41 gold badges320 silver badges351 bronze badges asked Feb 24, 2016 at 10:22 rwurrwur 2471 gold badge6 silver badges16 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 4

This does the trick:

$(".markDIV").on("click", function (evt) {
    if (evt.ctrlKey)
        $(this).toggleClass("marked");
});

Toggle a class on each clicked div, then get an array of the ids of the divs with the class. The clicking of CTRL is a little redundant when using div elements. Try this:

$(".myDivs").on("click", function() {
    $(this).toggleClass('selected');
    var selectedIds = $('.selected').map(function() {
        return this.id;
    }).get();
    console.log(selectedIds);
});

Example fiddle

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744993188a4605030.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信