[英]How do I get the ID of a particular class using jQuery?
我有一些具有类名称hover
div元素,这些div元素具有具有类名hoverparent
父div,但是这些父元素的id不同。
将.hoverparent
悬停在.hover
div元素上时,能否获取相应.hoverparent
元素的ID?
我试图通过以下方式获得此信息:
$('.hoverparent').attr('id')
但是,每次都给出相同的第一个父代ID。
结构就像:
<div class="hoverparent" id="hover-1">
<div class="hover">ABC</div>
</div>
<div class="hoverparent" id="hover-2">
<div class="hover">DEF</div>
</div>
在悬停回调中尝试$(this).parent()。attr('id')。
$('.hover').mouseover(function() {
$(this).parent().attr('id');
});
不要称呼您的课程悬停。 这应该工作
$(".hover").hover(
function () {
var id = $(this).parent().attr('id');
});
像这样添加每个循环:
$(".hoverparent").each(function(){
var id=$(this).attr("id");
alert(id);
});
在处理程序中将父方法用于悬停事件:
$('.hover').hover(function(evt){
var par = $(this).parent().attr('id');
//Now do with ID what you need
},
function(evt){
//presumably you don't need anything for mouseout
});
您可以尝试使用parent()方法。 像这样:
$('a').click(function(){
var parentId = $(this).parent('div.hoverparent').attr('id');
});
$(".hover").hover(function(){
console.log($(this).closest(".hoverparent").attr("id"));
});
请尝试以下操作:
$('.hover').hover(function() {
var parentID = $(this).parent().attr('id'); alert(parentID);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.