How to access attribute in jquery for a parent element undefined in firefox?

时间:2015-07-31 20:10:28

标签: jquery

HTML looks like this (using angular):

<div fruit="pear">
<a onclick="clickHander($event)"></a>
</div>

I want to access the "fruit" attribute in the parent. I tried:

var clickHandler = function(event) {
var fruit = $(event.target).parent().attr("fruit")
}

This works in chrome but not in Firefox as it says undefined. How do I get around this?

2 个答案:

答案 0 :(得分:2)

是的,您可以像以下一样(使用 JQuery data ):

HTML:

<div data-fruit="pear">
    <a href="#"></a>
</div>

JS:

$("a").click(function() {
    var fruit = $(this).parent().data("fruit");
});

答案 1 :(得分:1)

Try this:

<div data-fruit="pear">
    <a href="#"></a>
</div>
$("a").click(function() {
    var fruit = $(this).parent().attr("data-fruit");
});