我如何修改动态生成的html元素的样式?

时间:2016-06-29 17:39:48

标签: javascript html

我有这段代码:

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,但不起作用

1 个答案:

答案 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);
  }
}