开发者

Select 2 DIV elements

开发者 https://www.devze.com 2023-02-13 06:53 出处:网络
Im trying to figure out a simple way to enable me to select 2 DIV elements using JQuery - here is my attempt : h开发者_高级运维ttp://jsfiddle.net/MarKP/5/

Im trying to figure out a simple way to enable me to select 2 DIV elements using JQuery - here is my attempt : h开发者_高级运维ttp://jsfiddle.net/MarKP/5/

I need to limit the selections to just 2 and will use the class I add to get the selected objects.

Can anyone point me in a better direction

<div id="1">one</div>
<div id="2">two</div>
<div id="3">three</div>
<div id="4">four</div>

var selected = 0;
var prevSelect;
$('div').click(function() {
    if (selected == 2) {
        selected = 1;
        console.log(prevSelect);
        $('#' + prevSelect).removeClass('fill');
    }
    $(this).addClass('fill');
    prevSelect = $(this).attr('id');
    selected = selected +1;

});

div {
    border: 1px solid blue;
    height: 25px;
    margin-bottom: 5px;
}
.fill {
    background-color: red;
}


I updated your functionality to disallow any selection change if 2 divs are already selected unless you click a selected div to unselect it:

http://jsfiddle.net/MarKP/32/

$('div').click(function(e){
    var $et = $(e.target);
    if ($et.hasClass('fill')) { 
        $et.removeClass('fill');
    } else {
        if ($('.fill').length < 2) {
            $et.addClass('fill');
        }
    }
});

Old solution: http://jsfiddle.net/MarKP/11/


What you want is something like this:

$('.divclass').click(function(){
  var cnt=$('.divclass .selected').length;
  if(cnt>2) return;

  $(this).addClass('selected');
});

This will add the class selected to at most 2 divclass objects. To get the selected objects, you just call $('.divclass .selected').


If you always want to remove the oldest one clicked (unless it is already selected), I'd maintain my own array like this:

Example: http://jsfiddle.net/MarKP/17/

var selected = [];
$('div').click(function() {
    if( $.inArray( this, selected ) > -1 ) return;
    if( selected.length === 2 ) {
        $(selected.shift()).removeClass('fill');
    }
    selected.push($(this).addClass('fill')[0]);
});


Only add a selected class if there are fewer than two divs returned from a selector for div.selected. Otherwise, remove the selected class. For instance:

$('div').click(function() {
    if (!$(this).hasClass("selected") && $("div.selected").length < 2) {
        $(this).addClass("selected");
    } else {
        $(this).removeClass("selected");
    }
});
0

精彩评论

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