为什么addEventListener没有点击工作?

时间:2017-05-26 16:03:24

标签: javascript addeventlistener

这是代码,我无法触发点击事件监听器

使用Javascript:

var cid = 1721;
var alt = "4x6_" + cid;
var thumb = "168c619a1d1743bd4f3aba9d69a8c3ce";
var mattes_selected_type = "182";
var i = 0;
function common_get_site_url()
{
  return "https://jsfiddle.net/img/logo.png";
}

//
var thumb_img = new Image();
thumb_img.id = 'cid_' + cid;
thumb_img.alt = alt;
thumb_img.src = ""; 
thumb_img.addEventListener('load', function() {
   alert("LOAD");
}, false);
thumb_img.addEventListener('click', function() {
  alert("CLICK");
}, false);
thumb_img.src = common_get_site_url();

$('#matte_designs_strip_wrapper').append('<span class="matte_design_image_name"><img id="cid_' + cid + '" src="' + thumb_img.src +'" /></span>'); 

HTML:

<div id="matte_designs_strip_wrapper"></div>    

https://jsfiddle.net/allisonc/yoq4Lotx/1/

3 个答案:

答案 0 :(得分:9)

尝试将最后一行更改为:

$('#matte_designs_strip_wrapper').append($('<span class="matte_design_image_name"/>').append(thumb_img));

否则,您将addEventListener用于永远不会出现的元素

答案 1 :(得分:0)

您引用的是Image对象,而不是您期望的实际HTML元素。一旦您动态添加和添加HTML,就要运行

$('#cid_' + cid).on('click', function(e) {
  // Your code here
});

然后你的事件监听器将定位正确的HTML,而不仅仅是任何对象:)

答案 2 :(得分:0)

&#13;
&#13;
var cid = 1721;
var alt = "4x6_" + cid;
var thumb = "168c619a1d1743bd4f3aba9d69a8c3ce";
var mattes_selected_type = "182";
var i = 0;
function common_get_site_url()
{
  return "https://jsfiddle.net/img/logo.png";
}

//
var thumb_img = new Image();
thumb_img.id = 'cid_' + cid;
thumb_img.alt = alt;
thumb_img.src = ""; 
thumb_img.addEventListener('load', function() {
   alert("LOAD");
}, false);
thumb_img.addEventListener('click', function() {
  alert("CLICK");
}, false);
thumb_img.src = common_get_site_url();

var span = $('<span class="matte_design_image_name"></span>')

span.append(thumb_img)

$('#matte_designs_strip_wrapper').append(span);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="matte_designs_strip_wrapper"></div>
&#13;
&#13;
&#13;