获取<a> tag dynamically</a>的ID

时间:2013-11-05 17:23:54

标签: javascript

我必须创造一个&#39;调用函数(lect)时动态标记!在这个标签的onclick()事件中,我需要知道它的id。这是更清楚地解释问题的代码

function lect(j) {
    var mydiv = document.getElementById("cd" + j);

    var count = 3;
    for (var k = 1; k <= 3; k++) {
      var aTag = document.createElement('a');
      var inn = "analysis" + k;
      var id = "link" + k;
      var hr = "#";
      aTag.setAttribute('id', id);
      aTag.setAttribute('href', hr);
      aTag.innerHTML = inn;
      aTag.onclick = function (e) 
      { // here i want to get the id of tag, so that it could be passed to
        // the second html page  
        location.href = 'gallery-2.html?lectName=' + //name of id// ;
      };
    mydiv.appendChild(aTag);
    }
}

请帮帮我怎么做!

1 个答案:

答案 0 :(得分:1)

你可以这样做:

aTag.onclick = function (e) 
{
   location.href = 'gallery-2.html?lectName=' + this.id;
};

onclick事件中,this会引用aTag对象。