1

こんにちは、クリックした要素の親要素のクラスを取得しようとしています

元:

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

親div(mydiv)のクラスを取得したい

私はこれを試しましたが、うまくいきませんでした:

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

それは常に私に(未定義)を与えます。誰でも助けることができますか?

4

6 に答える 6

5

.parent()jqueryオブジェクトを提供し、classNameは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
于 2013-10-06T17:30:09.857 に答える
1

{リンク}を使用.attr()

$('.element').attr('class'); // Get class(es)
$('.element').attr('id'); // Get the ID
于 2013-10-06T17:30:06.480 に答える
1

使用.attr()してみてください:

$(document).ready(function(){
$(".link").click(function(){
var div=$(this).parent().attr('class');
alert(div);
});
});
于 2013-10-06T17:30:15.247 に答える