如何使用事件目标属性访问<li>元素中的特定值?

时间:2019-02-21 00:25:23

标签: javascript html css

说我只想访问已添加到在另一个函数内的for循环中创建的li元素中的c.symbol值。我将如何去做?

from django.db.models import QuerySet
from typing import Iterator, Union, TypeVar, Generic

T = TypeVar("T")

class ModelType(Generic[T]):
    def __iter__(self) -> Iterator[Union[T, QuerySet]]:
        pass

3 个答案:

答案 0 :(得分:1)

我建议您使用dataset属性存储要附加到元素的数据。

let data = [{
  symbol: "EleFromStack",
  companyName: "Stack"
}];

let companyList = document.getElementById("companyList");
for (let c of data) {
  let node = document.createElement('li');
  node.textContent = c.companyName + ', ' + c.symbol; //only want c.symbol
  node.dataset.symbol = c.symbol; // Here I'm storing the c.symbol value
  companyList.appendChild(node);
  node.addEventListener('click', function(e) {
    if (e.target && e.target.nodeName.toLowerCase() == "li") {
      populateCompanyInfo(e);
    }
  });
}

function populateCompanyInfo(e) {
  console.log(e.target.dataset.symbol)
}
<ul id="companyList">
</ul>

答案 1 :(得分:0)

您只需split中的textContent中的event.target即可获得c.symbol

function populateCompanyInfo(e) {
    var cSymbol = e.target.textContent.split(", ")[0];
    //Do something with cSymbol
}

答案 2 :(得分:0)

一种选择是保留匿名点击处理程序功能,复制c.symbol并将其作为参数传递给populateCompanyInfo

for(let c of data){
        let node = document.createElement('li');
        node.textContent = c.companyName + ', ' + c.symbol; //only want c.symbol
        companyList.appendChild(node);
        let cSymbol = c.symbol;
        node.addEventListener('click', function(e){
            populateCompanyInfo(e, cSymbol);
        });
    }  
function populateCompanyInfo(e, cSymbol){
    // c.symbol is the second argument.
}

如果您需要访问其他数据属性,也可以通过使用populateCompanyInfo作为参数调用c来传递整个数据对象:

 populateCompanyInfo( c); // if the event object is not needed