简体   繁体   English

如何查看首先单击哪个元素?

[英]How to see which element was clicked first?

I have a selection menu using toggleClass(). 我有一个使用toggleClass().的选择菜单toggleClass(). to see which menu options were selected: 查看选择了哪些菜单选项:

$('.img1, .img2, .text1, .tex2').click(function() {
    $(this).toggleClass('selected');
});

The way my selection menu works is that if two elements have the class selected then something will happen. 我的选择菜单的工作方式是,如果两个元素具有类selected ,然后会有些事情发生。 For example: 例如:

if ( $('.img1').hasClass('selected') && ('.text1').hasClass('selected') ) {
    // do something
}

This all works perfectly however I want to disable the user from picking two imgs or two texts . 这一切都很好,但是我想禁止用户选择两个imgs或两个texts The way I want to do this is just have the first selected element be removed from the selected class and the second selected element stay selected. 我要这样做的方法是将第一个选定的元素从选定的类中删除,而第二个选定的元素保持选中状态。 For example: 例如:

if ( $('.img1').hasClass('selected') && ('.img2').hasClass('selected') ) {
        // remove selected from the element that was first clicked and keep selected on the element that was clicked second
}

What would be the best way of achieving this? 实现这一目标的最佳方法是什么? Thanks in advance. 提前致谢。

Try: 尝试:

$('.img1, .img2').click(function() {
    $('.img1, .img2').removeClass('selected').filter(this).toggleClass('selected');
});
$('.text1, .text2').click(function() {
     $('.text1, .text2').removeClass('selected').filter(this).toggleClass('selected');
});

Separating your click events will ensure only one of each type of item is selected. 分开您的点击事件将确保仅选择每种类型的项目之一。

Also, make sure you aren't doing $('this') . 另外,请确保您没有做$('this')

It should be $(this) . 应该是$(this)

This will add the class name "first" to the first item that is clicked. 这会将类名“ first”添加到被单击的第一项。 The rest is up to you. 其余的取决于您。

$('.img1, .img2, .text1, .tex2').click(function() {
    $('this').toggleClass('selected');
    if($('.first').length==0) {
        $('this').addClass('first');
    }
})

perhaps if you had an array that kept track of the id of the clicked items, you could use that: 也许如果您有一个跟踪点击项ID的数组,则可以使用该数组:

var clickArr = new Array();
$('.img1, .img2, .text1, .tex2').click(function()
{
    $('this').toggleClass('selected');
    clickArr.push($(this).attr("id"));
});

then, when you find a spot where both are selected: 然后,当您找到一个同时选择了两个地点的地点时:

if ( $('.img1').hasClass('selected') && ('.img2').hasClass('selected') )
{
    $("#"+clickArr[0]).removeClass("selected");
    clickArr.shift();
}

This could be tricky because you will have to empty the array every time you "process a selection" that is valid. 这可能很棘手,因为每次“处理选择”有效时,您都必须清空数组。 But maybe this can get you started. 但这也许可以帮助您入门。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM