问题描述
需要制作一个Web部件,以JSON格式从API获取数据。我从JSON生成带有项目编号的表。然后,我将每个 td 更改为与class =“ project_number ”链接。
现在每个职位都有特定的班级。否,我不需要每个链接来直接指向项目详细信息或url,例如:https://XXX.azurewebsites.net/api/protocollines?protocolNo=PR0002
我不知道应该在querySelector中放置什么参数以使每个链接具有addEventListener。
document.querySelector("???").addEventListener('click',*function*);
function changeToLink(){
var tableCells = Array.from(document.getElementsByTagName('td'));
var i;
var proNo = "PR0";
for (i=0; i<tableCells.length; i++ && isContains == true) {
var proFromArray = tableCells[i].innerHTML;
var isContains = proFromArray.includes(proNo);
if(isContains == true){
var tdElement = document.getElementsByTagName('td')[i];
console.log('Profrom: ' + proFromArray);
tdElement.innerHTML = `<a class="${proFromArray}" href='https://XXX.azurewebsites.net/api/protocollines?protocolNo=${proFromArray}'>${proFromArray}</a>`
}
}
}
document.querySelector(`??`).addEventListener('click',*function*);
解决方法
有几种方法可以做到这一点。
选项1您可以使用JS创建锚元素,并在创建每个锚元素时添加onclick事件,例如:
// inside the if(isContains == true){
var a = document.createElement('a');
a.className = proFromArray;
a.href = `https://XXX.azurewebsites.net/api/protocollines?protocolNo=${proFromArray}`;
a.textContent = proFromArray;
a.onclick = this.getJsonData;
我创建了一个小提琴以演示其工作原理:https://jsfiddle.net/brettnolf/f3xd7ag1/
选项2现在,如果需要以字符串形式创建它,然后在创建的内容上调用querySelector
,则可以向每个锚标记添加相同的类:>
tdElement.innerHTML = `<a class="${proFromArray} pro-elem" href='https://XXX.azurewebsites.net/api/protocollines?protocolNo=${proFromArray}'>${proFromArray}</a>`
然后添加事件监听器,例如:
var pros = document.querySelectorAll('.pro-elem')
for (var i = 0; i < pros.length; i++) {
pros[i].addEventListener(this.getJsonData);
}
选项3
如果这两个解决方案都不可行,则可以使用查询选择器通配符并添加与上面类似的事件侦听器:
var pros = document.querySelectorAll('[class^=PR0]')
// or if you wanted to be really specific:
// document.querySelectorAll('td a[class^=PR0]')
for (var i = 0; i < pros.length; i++) {
pros[i].addEventListener(this.getJsonData);
}
如果您在https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll处拉起Chrome开发工具,然后在控制台中输入document.querySelectorAll('[class^=title]')
,则可以看到最后一个解决方案的作用。
请注意,最后两个选项仅在 元素添加到DOM后才起作用。在第一个选项中,您是在创建元素时添加侦听器的,因此您可以即时进行操作。