我试图找出一种简单的方法,使我能够使用 JQuery 选择 2 个 DIV 元素 - 这是我的尝试:http://jsfiddle.net/MarKP/5/
我需要将选择限制为 2 个,并将使用我添加的类来获取所选对象。
谁能给我指出更好的方向
<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;
}
最佳答案
我更新了您的功能,如果已选择 2 个 div,则不允许进行任何选择更改,除非您单击选定的 div 来取消选择它:
$('div').click(function(e){
var $et = $(e.target);
if ($et.hasClass('fill')) {
$et.removeClass('fill');
} else {
if ($('.fill').length < 2) {
$et.addClass('fill');
}
}
});
关于javascript - 选择 2 个 DIV 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5122732/