我有这段代码:
function createfunc(i) {
return function() {
document.getElementById('id'+i).style.color='red';
document.getElementById('id'+i).innerHTML = "Paragraph changed!";
}
}
function onDeviceReady() {
var olnew = document.createElement("ul");
for (i = 0; i < 10; i++){
var newLi = document.createElement("li");
var title = document.createElement('h2');
title.id="id"+i;
title.innerHTML = i;
newLi.appendChild(title);
newLi.onclick =createfunc(i);
olnew.appendChild(newLi);
}
}
但是当我点击li元素时,它不会改变颜色或文本
非常感谢
更新
原始代码是:
<html>
<head>
<script>
function createfunc(i) {
return function() {
document.getElementById('id'+i).style.color='red';
document.getElementById('id'+i).innerHTML = "Paragraph changed!";
}
}
function onDeviceReady() {
var olnew = document.getElementById('ordenes');
for (i = 0; i < 10; i++){
var newLi = document.createElement("li");
var title = document.createElement('h2');
title.id="id"+i;
title.innerHTML = i;
newLi.appendChild(title);
newLi.onclick =createfunc(i);
olnew.appendChild(newLi);
}
}
</script>
</head>
<body onload="onDeviceReady();">
<div id="layout">
<ul id="ordenes" ></ul>
</div>
</body>
</html>
当我点击li,没有变化时,li元素具有id,但不起作用
答案 0 :(得分:0)
不要维护ID
属性,而是使用this
中的handler-function
上下文代表Element
调用哪个事件,并使用querySelector
选择{{1}元素。
child
function createfunc() {
this.querySelector('h2').style.color = 'red';
this.querySelector('h2').innerHTML = "Paragraph changed!";
}
function onDeviceReady() {
var olnew = document.getElementById('ordenes');
for (var i = 0; i < 10; i++) {
var newLi = document.createElement("li");
var title = document.createElement('h2');
title.innerHTML = i;
newLi.appendChild(title);
newLi.onclick = createfunc;
olnew.appendChild(newLi);
}
}