Ornitier Ornitier - 1 year ago 92
jQuery Question

Error in event handler: "this.data() is not a function"

I have an HTML list of links with

attributes on each one:

<ul id="list">
<li><a data-info="link1"> **** </a></li>
<li><a data-info="link2">****</a></li>
<li><a data-info="link3">**** </a></li>
<li><a data-info="link4">****</a> </li>

I need to receive the
value of a link whenever it is clicked. So I thought something like this:

var my_links = $('#list').find('a');

my_links.on('click', function(){

But then I get:

Uncaught TypeError: this.data is not a function

If I just do:

var my_links = $('#list').find('a');

my_links.on('click', function(){

I get the complete HTML code of each link, for example:

<a data-info="link1"> **** </a>

why are both things happening, and how can I fix it?

Answer Source

data() is a jQuery method, not a method of native DOM objects. Your this is a native DOM element. Wrap it in jQuery first:

my_links.on('click', function(){

(and note that you don't have an info variable - you're looking for the data accessed by the string 'info')

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download