【问题标题】:array to HTML elements and append to ul数组到 HTML 元素并附加到 ul
【发布时间】:2021-03-05 23:04:29
【问题描述】:

当给定数组包含员工列表时

let names = [
  { firstName: 'John', lastName: 'Doe', DOB: '01Jan1970', role: 'cook' },
  { firstName: 'Mary', lastName: 'Jane', DOB: '11Sep2000', role: 'server' },
];

并且已经提供了#ul,

<ul id="container">
  <li>
    <a class="name">John Doe</a>
    <div class="age">41</div>
  </li>
  <li>
    <a class="name">Mary Jane</a>
    <div class="age">20</div>
  </li>
</ul>

我需要使它在单击名称时返回员工的角色,这是我的代码:

function printRole(user) {
  
  console.log(user.role);
}

function getRoles(array) {

    for (let i = 0; i < array.length; i++) {
        const li = document.createElement('li'),
            a = document.createElement('a'),
            div = document.createElement('div')
            //user = array[i]
        let selectedUser;
        let user = array[0]
        if (user.firstName === firstEl) {
            selectedUser = user;
            printRole(selectedUser)

            a.innerText = user.firstName + ' ' + user.lastName
            a.addEventListener("click", printRole(user))
        }
    }
}

我首先在 HTML 元素中使用了createElement,然后在某个时候添加了addEventListner。我知道我必须在某些时候将li 应用于#ul 容器,但我对自己做错了什么(也许是所有事情)感到非常困惑。 我相信我正朝着正确的方向前进,但我似乎不知道如何以一种像样的(正确的)方式来表达它。

【问题讨论】:

  • 你可以尝试像这样添加事件监听器。 a.addEventListener("click", () =&gt; printRole(user)) 因为addEventListener 需要回调函数。

标签: javascript html arrays dom


【解决方案1】:

试试这样:

let names = [{
    firstName: 'John',
    lastName: 'Doe',
    DOB: '01Jan1970',
    role: 'cook'
  },
  {
    firstName: 'Mary',
    lastName: 'Jane',
    DOB: '11Sep2000',
    role: 'server'
  },
];

getRoles(names);

function getRoles(array) {
  const container = document.getElementById('container');

  for (let i = 0; i < array.length; i++) {
    const li = document.createElement('li'),
      a = document.createElement('a'),
      div = document.createElement('div')

    let user = array[i];

    a.innerText = user.firstName + ' ' + user.lastName;
    a.className = 'name';
    a.addEventListener('click', function() {
      printRole(user);
    });

    div.className = 'age';
    div.innerText = getAge(user.DOB.substr(0,2) + ' ' + user.DOB.substr(2,3) + ' ' + user.DOB.substr(5));

    li.appendChild(a);
    li.appendChild(div);
    container.appendChild(li);
  }
}

function printRole(user) {
  console.log(user.role);
}

//getAge function from: https://stackoverflow.com/questions/10008050/get-age-from-birthdate
function getAge(dateString) {
  var today = new Date();
  var birthDate = new Date(dateString);
  var age = today.getFullYear() - birthDate.getFullYear();
  var m = today.getMonth() - birthDate.getMonth();
  if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
    age--;
  }
  return age;
}
&lt;ul id="container"&gt;&lt;/ul&gt;

创建的元素需要一起添加并添加为#container 的子元素。在事件侦听器函数中,使用特定参数 (user) 调用 printRole 需要包装在 addEventListener callback function 中。

【讨论】:

  • 感谢您的宝贵时间。不过,只有一件事,AssertionError: expected '&lt;a class="name"&gt;&lt;/a&gt;' to equal '&lt;a class="name"&gt;John Doe &lt;/a&gt;' 能否请您指导我了解为什么会出现此错误?
  • 您在哪一行收到该错误?我认为我们需要更多信息来确定发生这种情况的原因。
【解决方案2】:

你可以试试下面的代码。有什么不懂的可以随便问。

let list = [
  { firstName: 'John', lastName: 'Doe', DOB: '01Jan1970', role: 'cook' },
  { firstName: 'Mary', lastName: 'Jane', DOB: '11Sep2000', role: 'server' },
];
const container = document.querySelector('#container');
function renderList(list){
  list.forEach(obj => {
    const li = document.createElement('li');
    const a = document.createElement('a');
    const div = document.createElement('div');
    
    a.innerHTML = `${obj.firstName} ${obj.lastName}`;
    div.innerHTML = obj.DOB;
    
    a.addEventListener('click', () => {
      console.log(obj.role)
    })
    li.appendChild(a);
    li.appendChild(div);
    container.appendChild(li)
  })
}
renderList(list);
<ul id="container">
</ul>

【讨论】:

  • 谢谢,但我无法更改function getRoles(array) 虽然的名称,
  • AssertionError: expected '&lt;a&gt;Joe Blow&lt;/a&gt;' to equal '&lt;a class="name"&gt;Joe Blow&lt;/a&gt;' 我收到此错误消息,似乎我需要在 a 上添加一个类?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-04
  • 2018-08-27
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 2018-08-18
  • 2014-02-24
相关资源
最近更新 更多