2014-09-19 52 views
0

我在我自己的图像浏览器中建立一个函数,当用户将光标悬停在某个图像的div上时,创建并显示一个删除按钮,并在用户将鼠标悬停时隐藏按钮的div。动态添加按钮上点击不起作用

这是代码:

 function displayImages() { 
     //run through array of images 
     for (a = 0; a < images.length; a++) { 

var container = document.createElement('div'); 
       container.id = 'container'+images[a]; 
       container.style.width = 120; 
       container.style.backgroundColor = '#e9e9e9'; 
       container.style.height = 140; 
       container.style.margin = 5; 
       container.style.display = 'inline-block'; 
       container.style.float = 'left'; 
       var imageID = images[a]; 
       container.onmouseover = function() {imageRollover(this)}; 
       container.onmouseout = function() {imageMouseOut(this)}; 
    }  
    } 


function imageRollover(image) { 
     var trashcan = document.createElement('BUTTON'); 
     trashcan.id = 'trash'+image.id; 
     trashcan.className = 'deleteButton'; 
     trashcan.onclick = function() {deleteImage(image.id);}; 
     document.getElementById(image.id).appendChild(trashcan); 
    } 



function imageMouseOut(image) { 
    document.getElementById(image.id).removeChild(document.getElementById('trash'+image.id)); 
     } 

function deleteImage(image) { 
     alert(image); 
    } 

我的问题是,当我点击trashcan,它调用什么。我已经尝试通常添加onlick事件: trashcan.onclick = deleteImage(image.id); 但是,然后,由于某种原因,当我将鼠标悬停在container上时,会调用该函数。

如何确保点击事件中的动态添加滚动按钮的工作?

该功能可以在DE查看:http://www.imaginedigital.nl/CMS/Editor/ImagePicker.htmlhttp://jsfiddle.net/f239ymos/

任何帮助将高度赞赏。

+0

控制台中的错误消息?也许你想要trashcan.onclick = function(){deleteImage('''+ image.id +'''');};此外,如果图像是一个'img'标签,你不能有一个孩子 – mplungjan 2014-09-19 13:19:47

+1

你可以提供一个jsfiddle吗? – Alexandros 2014-09-19 13:22:42

+0

图像以3格显示:1个容器,一个图像预览,它是一个img标签,另一个div显示图像名称。 de容器是实际创建孩子的div,因此不会导致问题。 – Joris416 2014-09-19 13:22:57

回答

0

你迫使我在这里猜测(不提供小提琴),并创建一个我自己的场景,但从我的理解,你想要一个按钮不出现悬停,当按下删除图像,所以在这里一个working fiddle

悬停功能

$((document.body).on('mouseenter', '.test', function(){ 
    console.log('here'); 
    $(this).children('.test .x_butt').show(); 
}); 
$(document.body).on('mouseleave', '.test', function(){ 
    $('.test .x_butt').hide(); 
}); 

删除功能

$(document.body).on('click', '.x_butt', function(){ 
    $(this).parent().remove(); 
}); 

PS至于你的动态增加divs的问题,$(selector1).on('click','selector2', function() {...});处理它,只要selector1没有动态添加。 (selector2会是你想要的功能是对格)

window.onload = loadImages();window.onload = loadImages;

然后因为你传递一个对象,你可以改变demo with dynamically added elements(点击克隆)

+0

我不认为他在使用jQuery。 – KoenW 2014-09-19 13:39:46

+0

如果没有理由,他不能使用它,为什么不使用它:P – Alexandros 2014-09-19 13:41:08

+0

我认为一个链接到网站本身会更好。这是因为图像选择器会通过xmlhttprequests从这些图像所在文件夹中的API加载所有图像。这通常不会被jsfiddle加载。尽管如此,这里是:http://jsfiddle.net/f239ymos/ – Joris416 2014-09-19 13:53:23

0

首先改变

function imageMouseOut(image) { 
    document.getElementById(image.id).removeChild(document.getElementById('trash'+image.id)); 
} 

function imageMouseOut(image) { 
    image.removeChild(image.childNodes[0]); 
} 

但是,为什么不只是隐藏和显示垃圾桶呢?更清洁