说我只想访问已添加到在另一个函数内的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
答案 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