我正在尝试单击我创建的列表中的一个元素,如下所示:
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 vs innerHtml vs label vs text vs textContent vs outerText有关该主题的更多信息。
fiddle (带注释): 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
的内容。
更新的 fiddle : 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())
}
关于javascript - 单击列表中的一个元素 html5 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34042765/