1

list:

<ul class="div_chart1" data-quickcode="mac" data-questionid="1" >
    <li>
       <img src="inmark/pie_icon.jpg" class="pie_icon" onclick="ok()"/>
    </li>
</ul>

function:

function ok(){          
    console.log($(this).parent().parent().data('quickcode'));
    console.log($(this).parent().parent().data('questionid'));  
}

function ok() returns undefined. What is wrong with this?

clintgh
  • 2,039
  • 3
  • 28
  • 44

2 Answers2

6

Try to pass the this reference as an argument to the inline handler,

HTML:

<img src="inmark/pie_icon.jpg" class="pie_icon" onclick="ok(this)"/>

JS:

function ok(elem){          
    console.log($(elem).closest('ul').data('quickcode'));
    console.log($(elem).closest('ul').data('questionid'));  
}

DEMO


And the best way of doing this would be,

$('.pie_icon').click(function(e){
  e.stopPropagation();
  var parent = $(this).closest('ul');
  console.log(parent.data('quickcode'));
  console.log(parent.data('questionid'));  
});
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
1

this in your context is referring to global window object.

console.log(this); // Window {top: Window, window: Window, location: Location, external: Object, chrome: Object…}

So pass element object like,

<img src="inmark/pie_icon.jpg" class="pie_icon" onclick="ok(this)"/>  


function ok(element) {
    console.log($(element).parent().parent().data('quickcode'));
    console.log($(element).parent().parent().data('questionid'));
} // here is element is HTML element object. Just wrap it with jQuery to use jQuery function.

More about inline event handlers

Deepak Ingole
  • 14,912
  • 10
  • 47
  • 79