0

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 タグ内にリスナーを追加するにはどうすればよいですか?

4

1 に答える 1

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
});
于 2013-07-26T13:32:07.093 に答える