如何在具有相同类的子元素上使用带有 $(this) 的单击函数

How to use click function with $(this) on children elements with the same class?

本文关键字:this 函数 单击 元素 同类      更新时间:2023-09-26

我想创建带有国家/地区>区域>城市选择的下拉列表。第一个 ul 通过单击该跨度打开,其他设置为在悬停时显示(代码在底部)。

<input type="text" id="srch-area" alt="" class="c-textfield suggestionsInput " name="locationStr" maxlength="" size="" tabindex="3" title="" value="Deutschland" defaultvalue="" highlight="y" strict="y" autocomplete="off">
<span class="c-icon-arrow-green-down-left c-icon" id="loc-slctbx"></span>
<ul class="dropdown-location-ul" id="dropdown-country" style="display:none;">
    <li class="dropdown-location-li">
        <strong>Deutschland</strong>
        <ul class="dropdown-location-ul" style="display:none;">
            <li class="dropdown-location-li">
                <strong>Brandenburg</strong>
                <ul class="dropdown-location-ul" style="display:none;">
                    <li class="dropdown-location-li">
                        <strong>Oranienburg</strong>
                    </li>
                    <li class="dropdown-location-li">
                        <strong>Schwedt</strong>
                    </li>
                    ...
                </ul>
            </li>
            <li class="dropdown-location-li">
                <strong>Berlin</strong>
            </li>
            ...
        </ul>
    </li>
    <li class="dropdown-location-li">
        <strong>France</strong>
    </li>
    ...
</ul>
$('.dropdown-location-li').hover(function(){
    $(this).children('ul').css('left', $(this).parent('ul').width()+'px');
    $(this).children('ul').show();
}, function(){
    $(this).children('ul').hide();
});

这工作得很好,现在我需要在单击时将其更改为强标签内的位置名称。我尝试了下面的代码,但似乎 $(this) 选择元素和他的所有父母,但我只需要从我单击的那个中获取位置。请告诉我如何正确执行此操作?也许我有完全错误的方法来做到这一点,并且需要使用 id 和其他东西来制作所有内容,但我只是想尽量减少重复 js 的麻烦。

$('.dropdown-location-li').click(function(){
    $('#srch-area').val($(this).children('strong').text());
    $('#dropdown-country').hide();
});

这就是它在控制台中的显示方式。正如你所看到的,当我点击奥拉宁堡时,它也选择了勃兰登堡和德国,它们是我点击的元素的父级。控制台截图

您已经嵌套了.dropdown-location-li元素,因此单击会不断传播到其他 LI 元素,再次触发事件处理程序等。
您应该在第一次停止传播

$('.dropdown-location-li').click(function(e){
    e.stopPropagation();
    $('#srch-area').val($(this).children('strong').text());
    $('#dropdown-country').hide();
});

尝试使用 JQuery Find

$(this).

find('strong').text()