如何在具有相同类的子元素上使用带有 $(this) 的单击函数
How to use click function with $(this) on children elements with the same class?
我想创建带有国家/地区>区域>城市选择的下拉列表。第一个 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()
相关文章:
- 在另一个函数中使用变量this
- JavaScript 中的嵌套函数和 “this” 关键字
- javascript中对象构造函数中的var属性与this.properties
- 函数中this和var之间的区别
- 在JavaScript类型的函数中避免self-this
- 如何使用(this)访问Angular 2 http rxjs catch函数中的对象属性
- jQuery使用ajax自动完成问题-TypeError:this.source不是函数
- 为什么在这种情况下,“This”确实充当javascript函数中的私有成员
- TypeError:this.getAttribute不是一个函数-javascript
- 可以't获取setInterval函数以使用javascript中的this.function_name调用另一
- `当使用箭头函数时,“开发工具”中未定义“this”
- 从另一个函数获得$this值
- 我收到此错误Uncatch TypeError:this.getElements不是一个函数
- 在函数中获取正确的作用域(不使用that=this)
- jQuery双对象构造函数-例如$($(this))
- Yii ajaxbutton : 如何在成功回调函数中获取 $(this)
- 如何在嵌套函数中获取$(this)
- Javascript:在函数外获取“this”
- 带参数的“this”函数
- 我可以在angularjs的$scope函数中写一个this函数吗?