简体   繁体   English

我将如何在 <li> 元素使用事件目标属性?

[英]How would I access a specific value in an <li> element using the event target property?

Say I want to only access the c.symbol value that has been added to the li element created in the for loop within another function. 假设我只想访问已添加到在另一个函数内的for循环中创建的li元素中的c.symbol值。 How would I go about doing that? 我将如何去做?

for(let c of data){
        let node = document.createElement('li');
        node.textContent = c.companyName + ', ' + c.symbol; //only want c.symbol
        companyList.appendChild(node);
        node.addEventListener('click', function(e){
            if(e.target && e.target.nodeName.toLowerCase() == "li"){
                populateCompanyInfo(e);
            }
        });
    }  
function populateCompanyInfo(e){
    //I want to be able to access the c.symbol value in here using the taget

}

I recommend you to use dataset attribute for storing data you want to attach to elements. 我建议您使用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> 

You can just split the textContent of event.target to get c.symbol : 您可以split event.targettextContent splitc.symbol

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

One option is to keep the anonymous click handler function , copy c.symbol and pass it as an argument to populateCompanyInfo : 一种选择是保留匿名点击处理程序功能,复制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.
}

You could also pass the entire data object by calling populateCompanyInfo with c as its argument if you ever needed to access other data properties: 如果您需要访问其他数据属性,也可以通过使用c作为参数调用populateCompanyInfo传递整个数据对象:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM