2017-01-08 20 views
0

私はH2の要素の中に曜日を表示しようとしていますが、コンソールには「fdayのプロパティは未定義です」というメッセージが表示されます。以下は、追加しようとしているHTML要素です。 doHTML要素のデータ属性に正しくアクセスするにはどうすればよいですか?

<div class="flex-container col-xs-6" id="weekDay"> 
    <h2 data-fday="1"></h2> 
    <h2 data-fday="2"></h2> 
    <h2 data-fday="3"></h2> 
    <h2 data-fday="4"></h2> 
    <h2 data-fday="5"></h2> 
</div> 

for (var i = 0; i < 6; i++) { //Begin loop - loop over the object's next 5 days 
    const weekly_forecast = data.daily.data; 
    let today = moment().format('D MMM, YYYY');//Format the date in the form Day/Month/Year from moment.js library 
    const weekday = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]; 

    $('#day_'+[i]).append("<h3>"+weekly_forecast[i].apparentTemperatureMax + "<br></h3><P>" + weekly_forecast[i].summary + "</p>"); //append a <h2> within that div containing the day and <p> containing the high and low temperature for the day 
     //Get the day of the week... 
    let a = new Date(today); //parse current date 
    let nextDay = weekday[a.getDay()+i]; //(get the day of the week) 
    const dayData = $("#weekDay > h2").dataset.fday; //accessthe data-attribute of each H2 within #weekday 
    if (dayData = [i]) { //if the data attribute of the H2 element === i 
     $(this).append(nextDay); //append the current day of the week in the H2 
    } 

    console.log(nextDay); 

} 
+0

'$( "#平日> h2は")'実際には何も – Ted

+0

'.dataの( 'fday')' – haxxxton

+0

@Tedコンソールショーを動作するはずが返された場合、チェック[H2、H2 、h2、h2、h2、prevObject:r.fn.init [1]ログアウト6回 –

答えて

1

datasetは、DOM要素プロパティではありません。

また、あなたが

$("#weekDay > h2").eq(i).data('fday'); 

それともとしてDOMノードプロパティにアクセスするための

$("#weekDay > h2")[i].dataset.fday 
+0

.eq(i).data(attr);完璧に働いた –

0

$("#weekDay > h2").dataset.fday 

を変更してみてくださいループ内

を適切な要素のインデックスをターゲットにする必要があります

PURE JSを使用してそれを行うには2通りの方法があります。データセットを使用するか、getAttributeメソッドを使用します。

var test = document.getElementsByTagName('li'); 
 
console.log(test[1].dataset.id); 
 
var dataText = test[0].dataset.id + " " + test[1].dataset.id; 
 
document.getElementById('target').innerHTML = dataText; 
 

 

 
var dataTextAnotherApproach = test[1].getAttribute('data-id'); 
 
document.getElementById('target2').innerHTML = dataTextAnotherApproach;
<div id="test"> 
 
    <ul> 
 
    <li data-id="data 1">Hello</li> 
 
    <li data-id="data 2">Hello 2</li> 
 
    </ul> 
 
</div> 
 
<div id="target"></div> 
 
<div id="target2"></div>

関連する問題