[英]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.