例如我有简单的 html。
<body>
<div class="a">
<div class="child"></div> <!-- div element I click -->
<div class="childINeedToSelect"></div> <!-- div element I need to be selected -->
<div class="child"></div>
</div>
<div class="a">
<div class="child"></div>
<div class="childINeedToSelect"></div>
<div class="child"></div>
</div>
</body>
当我点击顶部第一个 child
类 div 时,我需要更改,例如,第一个 childINeedToSelect
类 div 的边框 ONLY。它们具有相同的父级 - a
类 div,但困难在于不止一个具有 a
类的元素。我已经尝试过:
$(document).ready(function () {
var child = $('.child');
child.bind('click', function() {
detectElement($(this));
});
});
var belt;
function detectElement(arrow) {
belt = arrow.parent('.a').children('childINeedToSelect').eq(1);
belt.css("background-color", "red");
}
如您所见,我正在尝试将 $(this)
作为参数发送到 detectElement()
以确定单击了哪个 div。但是我的目标 div
背景没有改变,当我稍后尝试使用元素 belt
时,它被 detectElement 检测到 ()
函数,Opera javascript 调试器给我错误
Unhandled Error: Cannot convert 'belt.css('marginLeft')' to object
排队
var currentMargin = parseInt(belt.css('marginLeft').toString().replace('px', ''));
但这行代码在调用 detectElement()
函数之前运行得很好;我究竟做错了什么?我应该如何选择我需要的元素?
最佳答案
我建议:
function detectElement(arrow) {
arrow.parent().find('.childINeedToSelect').css('background-color','red');
}
$(document).ready(function(){
$('.child').click(function(){
detectElement($(this));
});
});
或者您可以使用 nextAll()
方法来查找同级 childINeedToSelect
:
function detectElement(arrow) {
arrow.nextAll('.childINeedToSelect').css('background-color','red');
}
如果你应该有多个 .child
和 childINeedToSelect
元素,你可以将 :first
选择器传递到 nextAll( )
方法:
function detectElement(arrow) {
arrow.nextAll('.childINeedToSelect:first').css('background-color','red');
}
我不确定您为什么要使用 bind()
,但如果您可能尝试考虑动态添加的元素(添加 < em>after 事件处理程序绑定(bind)到各种 DOM 节点/jQuery 对象),您可以改为使用 on()
:
$('.a').on('click','.child', function(){
detectElement($(this));
});
引用资料:
- >
find()
. - >
:first
selector . - >
nextAll()
. - >
on()
. - >
parent()
.
关于javascript - 如何通过在 jQuery 中单击同一父级的另一个子 div 来选择一个子 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12994126/