Frage

I want to add a listener inside of the img tag.

'<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() {

  });

So I get the img id and put it into goog.events.listen. However I got
goog.dom.getElement(downloadLeft_) is null. Why the getElement is null? how can I add listener inside of img tag?

War es hilfreich?

Lösung

To add a listener, you must have a reference to a DOM Node - not a string. Here's an example:

// 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
});
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top