this.value在td值上返回undefined

时间:2014-01-08 13:51:20

标签: javascript jquery

我试图获取表格中特定值的值。使用以下jQuery:

$( 'td.calendar-day' ).click(function() {
console.log(this);

返回

<td class="calendar-day" value="2014-01-03">
<div class="day-number">3</div>
<div class="class"><a href="http://website.com" target="_blank">2</a></div>
<div class="class"><a href="http://website.com" target="_blank">2</a></div>
<div class="class"><a href="http://website.com" target="_blank">2</a></div>
<p>&nbsp;</p>
<p>&nbsp;</p>
</td>

当我点击以下单元格时

<td class="calendar-day" value="2014-01-03">

但是当我添加:

console.log(this.value);

返回:undefined

非常感谢任何帮助。谢谢!

4 个答案:

答案 0 :(得分:7)

使用data- *属性。表行不应该具有值属性。最佳做法是设置数据属性,然后抓住它

<强> HTML

<td class="calendar-day" data-value="2014-01-03">

<强>的js

$('td.calendar-day').click(function() {
    this.getAttribute('data-value') // compatible with all browsers and also the most performance efficient. See benchmark below
    // Or .. $(this).data('value')
    // Or .. this.data.value
}

Benchmark Test 由@crush提供

答案 1 :(得分:2)

尝试

 $( 'td.calendar-day' ).click(function() {
   console.log($(this).attr('value'));
});

答案 2 :(得分:1)

你可以这样做:

console.log(this.getAttribute("value"));

但正如已经指出的那样,表行不应该具有值属性。

答案 3 :(得分:0)

请改为尝试:

console.log($(this).prop("value"));