0

I have several li element in page:

<li value="a">a</li>
<li value="b">b</li>
<li value="c">c</li>
<li value="d">d</li>

the I want get the value property when hover on it:

$(function () {
    $('li').live('mouseover', function () {
        console.log($(this).prop('value'));                             
    })
});

but the result is always 0,then I try the attr() method, it still can not work ,how can I solve this problem?

hh54188
  • 13,085
  • 30
  • 99
  • 174

5 Answers5

0

li elements do not have a value property.

For storing your own meta-data against an element you should use HTML5 data-* attributes:

<li data-value="a">a</li>
<li data-value="b">b</li>
<li data-value="c">c</li>
<li data-value="d">d</li>

Then use the jquery .data() method to retrieve them:

$(function () {
    $('li').live('mouseover', function () {
        console.log($(this).data('value'));                             
    })
});
Jamiec
  • 118,012
  • 12
  • 125
  • 175
0

Hmmm, I replicated this in a fiddle, even doesn't work using .val either. Probably because value is only designed for form fields. A solution is to change the value to a data attribute, like so:

<li data-value="a">a</li>
<li data-value="b">b</li>
<li data-value="c">c</li>
<li data-value="d">d</li>​

$(function () {
    $('li').live('mouseover', function () {
        alert($(this).data("value"));                             
    });
});​

Try this Fiddle

mattytommo
  • 52,879
  • 15
  • 115
  • 143
0

A <li> element cannot have a value attribute. If you want to define your own custom attributes, prefix them with data-.

<li data-value="a">a</li>
<li data-value="b">b</li>
<li data-value="c">c</li>
<li data-value="d">d</li>

Then change the name in your JavaScript code:

$(function () {
    $('li').live('mouseover', function () {
        console.log($(this).prop('data-value'));                             
    });
});

jQuery also lets you easily access data- attributes using $.data().

        console.log($(this).data('value'));
Mattias Buelens
  • 17,720
  • 4
  • 40
  • 49
0

Instead You can do this

$(function () 
{
    $('li').hover( function () {
        console.log($(this).attr('value'));                             
    })
});
Kabilan S
  • 1,094
  • 4
  • 15
  • 31
0

It Works Checked !!

$(function ()
{
    $('li').hover( function () {
        alert($(this).text());                             
    })
});
Kabilan S
  • 1,094
  • 4
  • 15
  • 31