Javascript 如何通过在jQuery中单击同一父级的另一个子div来选择一个子div?
例如,我有简单的htmlJavascript 如何通过在jQuery中单击同一父级的另一个子div来选择一个子div?,javascript,jquery,selector,Javascript,Jquery,Selector,例如,我有简单的html <body> <div class="a"> <div class="child"></div> <!-- div element I click --> <div class="childINeedToSelect"></div> <!-- div element I need to be selected --> &
<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>
如您所见,我正试图将$(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()
函数之前,这行代码工作得非常好;我做错了什么?我应该如何选择我需要的元素?
试试像这样的东西
jQuery('.a').children().first().click(function(){
jQuery('.childINeedToSelect').attr('background-color','red');
)}
我建议:
function detectElement(arrow) {
arrow.parent().find('.childINeedToSelect').css('background-color','red');
}
$(document).ready(function(){
$('.child').click(function(){
detectElement($(this));
});
});
或者,您可以使用nextAll()
方法查找同级childined以选择
:
function detectElement(arrow) {
arrow.nextAll('.childINeedToSelect').css('background-color','red');
}
如果您应该有多个.child
和childined来选择元素,您可以将:first
选择器传递到nextAll()
方法:
function detectElement(arrow) {
arrow.nextAll('.childINeedToSelect:first').css('background-color','red');
}
我不确定您为什么要使用bind()
,但如果您可能试图说明动态添加的元素(在事件处理程序绑定到各种DOM节点/jQuery对象后添加),您可以改为使用on()
:
参考资料:
belt=arrow.parent('.a')。childINeedToSelect('childINeedToSelect')。eq(1);不是有效的selectore,那里只有一个对象,因此它是.eq(0),但您甚至不需要使用此选择器模式的eq…而且children('childINeedToSelect')
缺少表示类的点前缀。您确实非常受欢迎,我很高兴能够提供帮助!=)
function detectElement(arrow) {
arrow.nextAll('.childINeedToSelect').css('background-color','red');
}
function detectElement(arrow) {
arrow.nextAll('.childINeedToSelect:first').css('background-color','red');
}
$('.a').on('click','.child', function(){
detectElement($(this));
});