将侦听器添加到由字符串连接创建的元素

时间:2013-07-24 20:04:42

标签: javascript closures google-closure-library

我想在img标签内添加一个监听器。

'<div id="111" style="height:20px; width:49.9%; float:left">'+
  '<span style="float: right; margin-right: 25px; margin-top: 4px;">'+
  '<img id= "',
  downloadLeft_,'" style="position:absolute;" src="/public/images/excel.gif"></span></div>'

  goog.events.listen(goog.dom.getElement(downloadLeft_), goog.events.EventType.CLICK, function() {

  });

所以我得到了img id并将其放入goog.events.listen中。但是我得到了 goog.dom.getElement(downloadLeft_)为null。为什么getElement为null?如何在img标签内添加监听器?

1 个答案:

答案 0 :(得分:1)

要添加侦听器,您必须具有对DOM节点的引用 - 而不是字符串。这是一个例子:

// Get a element to set the innerHTML contents on
var div = document.createElement('div');

// Add html created by strings
div.innerHTML = '<span style="float: right; margin-right: 25px; margin-top: 4px;">'+
    '<img id= "' + downloadLeft_ + '" style="position:absolute;" ' +
    'src="/public/images/excel.gif"></span>';

// Add the div to the document
document.documentElement.appendChild(div);

// Get a reference to the image element
var img = document.getElementById(downloadLeft_);

// Add listener
goog.events.listen(goog.dom.getElement(downloadLeft_),
    goog.events.EventType.CLICK, function() {
  //event listener code
});