我试图单击这样创建的列表的元素:
function addlist2(nombre,fecha){
var node = document.createElement("LI");
var textnode = document.createTextNode(nombre+" ");
var textnode2 = document.createTextNode(fecha);
node.appendChild(textnode);
node.appendChild(textnode2);
document.getElementById("lista").appendChild(node);
alert(document.getElementById(nombre).value);
}
但是我不知道我创建的每个元素的ID。当我单击列表的不同元素时,我想做不同的事情,例如打开不同的窗口或执行不同的功能:例如:
我的清单:
狗
猫
鸟
我在调用addlist2(“ dog”,“”);时创建了此元素。现在,我要显示“您已经单击了DOG”。
在此答案的底部进行更新以适应评论
您实际上并不需要id
每个列表项。
另外,根据您li
的内容,您可能希望textContent
代替使用innerHTML
来检查内容。有关该主题的更多信息,请参见innerText,innerHtml,label,text,textContent,outerText。
小提琴(附评论): http : //jsfiddle.net/c19u7074/3/
的HTML
<ul id="lista">
</ul>
的JavaScript
function addlist2(nombre, fecha) {
var node = document.createElement("li");
var textnode = document.createTextNode(nombre + " ");
var textnode2 = document.createTextNode(fecha);
node.appendChild(textnode);
node.appendChild(textnode2);
document.getElementById("lista").appendChild(node);
// Add a listener to the node
node.addEventListener("click", clickHandler);
}
function clickHandler(e) {
// Get node content as a string
var nodeText = e.target.textContent;
// Trim whitespaces from the string and check if they match any criteria you like
switch (nodeText.trim()) {
case "dog":
// It's a dog! So do dog stuff here
alert("woof woof");
break;
case "bird":
// It's a bird! So do bird stuff here
alert("tweet tweet");
break;
default:
// Else, do stuff below
}
}
addlist2("dog", "");
addlist2("bird", "");
正如您在对这个答案的评论中所问的那样:可以打开一个具有固定URL和可变部分(取决于li
s的内容)的窗口。
更新的小提琴: http : //jsfiddle.net/c19u7074/4/
更新了Javascript(仅clickHandler
更新了函数)
function clickHandler(e) {
// Get node content as a string
var nodeText = e.target.textContent;
// Open a window pointing to a fixed URL with a variable part containing the clicked item's contents
// Trim whitespaces from the string and check if they match any criteria you like
window.open('https://www.google.be/?q=' + nodeText.trim())
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句