2016-05-12 53 views
1

我試圖選擇具有class of hours的頁面上的所有TD標籤,並讀取每個數據屬性(月份的短名稱),然後將該值添加到<td></td>。像<td>40 Dec </td>查找所有TD標籤並讀取它們的數據屬性

由於我沒有得到任何價值,所以我的腳本出了問題,但是我錯過了什麼或者錯了什麼?

我的jQuery:

$("tbody").find("td").each(function() { 
 
    if ($(this).hasClass("hours")) { 
 
     var d = $(this).data("date"); 
 
     $(this).append("<br>" + d); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<tbody> 
 
    <td data-date="dec" data-activityid="7" data-resourceid="1" data-projectid="2" class="workingHours-ok hours">40</td> 
 
</tbody>

回答

3

只需使用append(function),它遍歷元素和追加返回的HTML代碼。因此,在幫助函數中獲取數據屬性值並將其返回。

$('td.hours').append(function() { 
 
    return '<br>' + $(this).data('date'); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table> 
 
    <tr> 
 
    <td data-date="Dec" class="hours">40</td> 
 
    <td data-date="Jan" class="hours">50</td> 
 
    </tr> 
 
    <tr> 
 
    <td data-date="Feb" class="hours">60</td> 
 
    <td data-date="Mar" class="hours">70</td> 
 
    </tr> 
 
    <tr> 
 
    <td data-date="Jan" class="hours">60</td> 
 
    <td data-date="Mar" class="hours">70</td> 
 
    </tr> 
 
</table>

3

你並不需要使用each()。你可以像下面這樣做。

$('td.hours').text(function (index, text) { 
 
    return text + ' ' + this.dataset.date; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table> 
 
    <tr> 
 
     <td data-date="Dec" class="hours">40</td> 
 
     <td data-date="Jan" class="hours">50</td> 
 
    </tr> 
 
    <tr> 
 
     <td data-date="Feb" class="hours">60</td> 
 
     <td data-date="Mar" class="hours">70</td> 
 
    </tr> 
 
</table>

+0

孩子你能避免調用'jQuery的()'再次'.text(function(index,text){})' – guest271314

0

假設你在標記有tbody,試試這個

$("tbody td.hours").each(function() { 
    $(this).append("<br>" + $(this).data("date")); 
}); 

或者乾脆

$("td.hours").each(function() { 
    $(this).append("<br>" + $(this).data("date")); 
}); 

,或者使用簡單attr如果數據日期設置動態

$("td.hours").each(function() { 
    $(this).append("<br>" + $(this).attr("data-date")); 
}); 
1

因爲你$(本)。數據( 「DATE」)。這是不應該working.You使用$(本)。數據( '日期') 當然,你的選擇就應該像

$("#yourtableid > tbody td.hours").each(function(){ 
var d= $(this).data('date');//and so on//}) 
0

它是你的代碼,因爲它只是前加<table> 210,因爲在你的代碼,<tobody>不是父母<td>,除非使用`的text`論點是的<table>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 

 

 
<table><tbody> 
 
    <td data-date="dec" data-activityid="7" data-resourceid="1" data-projectid="2" class="workingHours-ok hours">40</td> 
 
</tbody></table> 
 

 

 
<script> 
 
$("tbody").find("td").each(function() { 
 
    if ($(this).hasClass("hours")) { 
 
     var d = $(this).data("date"); 
 
     $(this).append("<br>" + d); 
 
    } 
 
});</script>

相關問題