高效的jquerydom遍历
考虑以下HTML:高效的jquerydom遍历,jquery,html,dom,traversal,Jquery,Html,Dom,Traversal,考虑以下HTML: <div class="group"> <div class="select">Project Type</div> <div class="option"> <div>Personal Website</div> <div>Business Website</div> <div>Hosting</d
<div class="group">
<div class="select">Project Type</div>
<div class="option">
<div>Personal Website</div>
<div>Business Website</div>
<div>Hosting</div>
<div>Social Media</div>
<div>Online Storefront</div>
<div>Graphics & Branding</div>
</div>
</div>
这是可行的,但我的问题是,我不认为这是非常灵活的,因为如果我以任何方式重新排列代码,它很容易被破坏,因为.select必须与.option相邻且在其之前,否则它会被破坏
有没有人有什么好的解决方案可以帮助我更动态地遍历DOM树,从而不依赖于HTML元素的确切顺序
$(".group").on('click', '.option div', function(event) {
// event.delegateTarget is always .group element
var test = $(event.delegateTarget).find('.select');
console.log(test);
console.log('Clicked option:', this);
});
阅读更多关于和的信息。您应该改用:
$(this).最近的('.group').find('.select')
更灵活的是,item.on('click',function(event){…})
对
中的每个子项进行单独绑定。为什么不使用$('.option')。在('click',函数(事件){…})
?在事件处理程序内部,您可以使用event.target
获取单击的子元素
。事件处理程序中的$(this).prevAll('.select')
或$(this).closest('.group').find('.select')
将从div.select元素中获取您的值。
$(".group").on('click', '.option div', function(event) {
// event.delegateTarget is always .group element
var test = $(event.delegateTarget).find('.select');
console.log(test);
console.log('Clicked option:', this);
});