2013-10-06 35 views
0

嗨,大家好,我試圖讓類,我點擊得到父HTML元素的類

防爆元素的父元素:

<div class="mydiv"><a href="#" class="link">Click me</a></div> 

我想要得到的類母公司股利(mydiv)

我試過,但沒有奏效:

$(document).ready(function(){ 
$(".link").click(function(){ 
var div=$(this).parent().className; 
alert(div); 
}); 
}); 

它總是給我(未定義) 。任何人都可以幫忙?

+6

*「P.S:我是jquery的新手,你不需要爲你看到的每一個錯誤都加上-1。」*強烈建議在你的問題中留下那些不相關的東西。如果問題得到妥善解答,人們不會降低問題的質量。如果不是這樣,那麼至少和那裏一樣,它會得到低估。 –

+0

完成了男人感謝您的警告 – caesar

回答

5

.parent()給jQuery對象和類名是DOM元素的屬性,以便嘗試:

var div=$(this).parent()[0].className; // use [0] to get the DOM element and get the property 

var div= $(this).parent().attr("class"); //Use jquery attr to get the value of the attribute class 
+2

獲取'className'的jQuery Way™將使用'$(this).parent()。prop('className')',但在這種情況下確實無關緊要。 – zzzzBov

+1

@zzzzBov真的,事實上,你可以使用道具(「類」)以及... – PSL

+0

你搖滾的人非常感謝 – caesar

1

使用.attr(){link}

$('.element').attr('class'); // Get class(es) 
$('.element').attr('id'); // Get the ID 
1

使用.attr()嘗試:

$(document).ready(function(){ 
$(".link").click(function(){ 
var div=$(this).parent().attr('class'); 
alert(div); 
}); 
}); 
1

className是HTML元素的一個屬性,而不是jQuery對象,比如$(this).parent()。您可以使用:

$(this).parent()[0].className; 

其訪問表示對象($(this).parent()[0])的DOM對象,然後查找該className財產。

請注意,如果您將多個類應用於某個元素,則className屬性將返回一個由所有類名稱分隔的空格組成的字符串。

https://developer.mozilla.org/en-US/docs/Web/API/element.className

了新版瀏覽器,你可以使用classList屬性,這使得帶班更容易處理:

https://developer.mozilla.org/en-US/docs/Web/API/element.classList

1

試試這個..... $(this).parent().attr('class'); ......敢肯定這樣的將工作:)

1

這應該得到的工作:

var parentClass = $('#childElement').parent().attr('class');