繁体   English   中英

如何正确访问HTML元素的数据属性?

[英]How do I properly access the data-attribute of an HTML element?

我试图将星期几显示在我的H2元素中,但控制台显示“无法读取fday的属性未定义”,以下是我尝试附加的HTML元素以及我正在使用的JS

<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);

}

dataset不是jQuery对象的属性,而是dom元素的属性。

另外,您还需要在循环中定位适当的元素索引

尝试改变

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

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

或作为dom节点访问属性

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

使用PURE JS有两种方法。 使用数据集或使用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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM