There are 10 ps, and there will be a highlight prompt when clicking, but you can only click two at a time. It is not a checkbox but a simple p containing content, or 10 different paragraphs of text. How to implement it with js?
Add a checked attribute to each p, the default is false, p[i].checked = false;
Change the checked attribute of current p while clicking, p[i].checked = !p[i].checked
While clicking p, traverse all the checked attributes of p. If two of them are checked, return false to exit the function. Otherwise, negate and assign the checked attribute of p. There are also some specific conditions to judge, and you can come up with it slowly according to your ideas.
$(document).on('click', '.demo', function() {
$(this).addClass('active');
var len = $('.active').length;
//初始化处理最开始的两次点击
if (len === 1) {
$(this).addClass('c-1');
}
if (len === 2) {
$(this).addClass('c-2');
}
//当已经有两个高亮,再次点击会取消最靠前一次点击的高亮
//例如:先点击4和6,再点2则最靠前的4会被取消,再点7则最靠前的6又会被取消
if (len === 3) {
$('.c-1').removeClass('c-1 active');
$('.c-2').removeClass('c-2').addClass('c-1');
$(this).removeClass('c-1').addClass('c-2');
}
});
Note: The reason why c-1 and c-2 identifiers are used here instead of index to get active elements, such as $('.active').eq(0), is because index has a sequential order, which will lead to clicks. One of the elements before or after a highlighted element is always invalid.
General idea
Add a checked attribute to each p, the default is false,
p[i].checked = false;
Change the checked attribute of current p while clicking, p[i].checked = !p[i].checked
While clicking p, traverse all the checked attributes of p. If two of them are checked, return false to exit the function. Otherwise, negate and assign the checked attribute of p. There are also some specific conditions to judge, and you can come up with it slowly according to your ideas.
Give you an example - -
View the example directly: https://jsfiddle.net/677a1m6z/1/
html
css
js
Note: The reason why c-1 and c-2 identifiers are used here instead of index to get active elements, such as $('.active').eq(0), is because index has a sequential order, which will lead to clicks. One of the elements before or after a highlighted element is always invalid.