如何从作为目标元素的表中获取价值?

时间:2019-02-18 08:25:58

标签: javascript html-table innerhtml target

我有一个html页面(带有javascript和json文件),其中有带有eventlistener keyup的Customer搜索/过滤器。我想要实现的是,将选定的表行添加到localstorage并添加到另一个表中对所有值求和。自定义搜索/过滤器效果很好。

class Item {
  constructor(name, price, stock) {
    this.name = name;
    this.price= price;
    this.stock = stock;

  }
}

searchFilter(e) {
    const input = e.target.value.toLowerCase();
    const tbody = document.querySelector('#search-output');
    const results = document.querySelector('#search-item');
    //Get json    
    const xhr = new XMLHttpRequest();
    xhr.open('GET', `item.json`, true);
    xhr.onload = function () {
      if (this.status === 200) {
        const response = JSON.parse(this.responseText);
        let content = '';
        response.forEach(function (item) {


          if (item.Description.toLowerCase().includes(input)) {
            results.style.display = "block";
            content += `<tr><td>${item.Description} </td>
                                   <td>${(item.Price).toFixed(2)} </td>
                                   <td">${item.Stock}g</td>
                                  //Here I add an icon that Users can click on it to add them after searching
                                   <td><a href="#" class="add-item secondary-content">&nbsp <i class="fa fa-plus"></i></a></td></tr>`;
          }
          //If not keep content empty and dont show tbody
          if (input === '') {
            content = '';
            results.style.display = "none";
          }
        });
        //Pass content into tbody
        tbody.innerHTML = content;
      }
    }
    xhr.send();
    e.preventDefault();
  }
}

然后我添加了我的活动监听器,点击了搜索区域

document.getElementById('search-output').addEventListener('click', function (e) {
  const ui = new UI();  
  ui.addFromSearch(e.target)

  e.preventDefault();

})

但是通过addFromSearch函数,事情变得越来越复杂

addFromSearch(target) {
//This is the table where I want to pass selected item
const list = document.getElementById('total-item-list');

//If clicked object if fa fa-plus
    if (target.className === 'fa fa-plus') {
      // with 3 parentElement up I have the desired tr and I can pass it to list where I want to show all seleected items
      const tr = target.parentElement.parentElement.parentElement;
      list.appendChild(tr);     
    }
  }

一切正常,直到这里,但是问题是我在const tr中有值,我必须将开始时创建的Object传递给Object,tr值如下所示。但这不是一个对象,因此无法使用tr.Children [i]获取值。您现在建议我做什么?

<tr><td>Item1 </td>
  <td>12,50 </td>
 <td">25</td>
    <td><a href="#" class="add-item secondary-content">&nbsp <i class="fa fa-plus"></i></a></td></tr>

0 个答案:

没有答案