首页 > 解决方案 > 从 DOM 访问元素

问题描述

我使用 jquery 动态创建元素。这是我的代码

function showArticles(res) {
    var output = '';
    res.articles.forEach(function (item) {
      output +=
        '<div class="col-12 col-lg-4 item-article" data-name="'+ item.author +'>'+
          '<p>' + item.description + '</p>'

          +
        '</div>'
      });
    articleWrapper.append(output);

我想访问该data-name属性

var itemArticle = $('.item-article').attr("data-type");
console.log(itemArticle)

返回undefined

如何访问data-name属性为什么会发生这种情况?

标签: javascript

解决方案


您可以使用var itemArticle = $('.item-article').data("name");


推荐阅读