简体   繁体   English

jQuery 触发单击具有特定属性的第一个元素

[英]jQuery trigger click on first element with specific property

I am making a search for my dropdown menu and I have some problems.我正在搜索我的下拉菜单,但遇到了一些问题。 When you search my dropdown by typing on keyboard the elements with your search change background color.当您通过在键盘上键入来搜索我的下拉列表时,您搜索的元素会更改背景颜色。 Now what I would like it is to trigger click event when you search and press enter after finding country you want (if there is more then one country enter should select first one).现在我想要的是在您搜索并在找到您想要的国家后按 Enter 时触发点击事件(如果有多个国家,则输入应选择第一个)。 I'm using background color to find elements that I need for enter key.我正在使用背景颜色来查找enter键所需的元素。 Here is my attempt to achieve this:这是我实现这一目标的尝试:

function enterTest() {

    $('.dropdown').on('show.bs.dropdown', function() {
        $(document.body).on('keypress', addClick);
    })

    $('.dropdown').on('hide.bs.dropdown', function() {
        $(document.body).off('keypress', addClick);
    })

    function addClick (e) {
        var key = e.which;
        var $background = $('.dropdown-menu ul li a').css('background-color');

        if (key == 13 ) {
            if ($background == 'rgba(255, 171, 0, 0.15)') {
                $('.dropdown-menu ul li a:eq(0)').click();
            }
        }
    }
}

$('.dropdown-menu ul li a:eq(0)').click(); When I use this part it always selects first element from the all a elements, but what I need is to select first element with rgba(255, 171, 0, 0.15) .当我使用这部分时,它总是从所有a元素中选择第a元素,但我需要的是用rgba(255, 171, 0, 0.15)选择第一个元素。 I have tried to use eq() like this: $(this).eq(0).click() but this also didn't work.我曾尝试像这样使用 eq(): $(this).eq(0).click()但这也不起作用。 I have also tried to do something like this:我也试过做这样的事情:

    if (key == 13 ) {
        $background.each(function (i) {
            if ($background == 'rgba(255, 171, 0, 0.15)') {
                $(this).click();
                return;
            }
        })
    }

but this also didn't work.但这也不起作用。
Is there a way to trigger click event to first element with specific color ?有没有办法触发具有特定颜色的第一个元素的点击事件? Can anyone help me solve this ?谁能帮我解决这个问题? Here is the codepen with example of my search without the function above https://codepen.io/Karadjordje/pen/MEBjRY这是带有我的搜索示例的代码笔,没有上面的功能https://codepen.io/Karadjordje/pen/MEBjRY

$('.dropdown-menu ul li a').filter(function(){
    $bg = $(this).css('background-color');
    if ($bg === 'rgba(255, 171, 0, 0.15)') {
        return true;
    }
}).eq(0).click();

The .filter part filters your results down to whatever you return true for, which in this case is the background color. .filter部分将您的结果过滤为您返回 true 的任何内容,在这种情况下是背景颜色。 .eq(0) gets those filtered results and only gives back the first one, and obviously .click() clicks it. .eq(0)得到那些过滤后的结果,只返回第一个,显然.click()点击它。

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

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