Javascript 单击“不工作”时动态添加的按钮
我正在自己的图像浏览器中构建一个函数,当用户将光标悬停在某个图像的div上时,它会创建并显示一个delete按钮,当用户将鼠标悬停在div外时,它会隐藏该按钮 代码如下:Javascript 单击“不工作”时动态添加的按钮,javascript,html,css,Javascript,Html,Css,我正在自己的图像浏览器中构建一个函数,当用户将光标悬停在某个图像的div上时,它会创建并显示一个delete按钮,当用户将鼠标悬停在div外时,它会隐藏该按钮 代码如下: function displayImages() { //run through array of images for (a = 0; a < images.length; a++) { var container = document.createElement('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);
}
我的问题是,当我点击垃圾桶时,它什么也不叫。我已尝试正常添加onlick事件:
trashcan.onclick=deleteImageimage.id;
但是,出于某种原因,当我将鼠标悬停在容器上时,is调用了该函数
如何确保动态添加的滚动按钮的点击事件有效
该功能可在以下位置取消查看:或
任何帮助都将不胜感激。你强迫我猜这里,不给小提琴,并创建一个我自己的场景,但据我所知,你希望一个按钮显示为无悬停,当按下时删除图像,因此这里是一个 悬停功能
$((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();
});
删除功能
$((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();
});
另外,对于动态添加的divs问题,$selector1.on'click','selector2',函数{…};只要selector1不是动态添加的,就可以处理它。选择符2将是您希望函数在单击“克隆”时显示的div
window.onload=加载图像;to window.onload=loadImages
那么,既然你传递了一个对象,你就可以改变它
function imageMouseOut(image) {
document.getElementById(image.id).removeChild(document.getElementById('trash'+image.id));
}
到
然而,为什么不把垃圾桶藏起来展示呢?控制台中的错误消息要干净得多?也许您需要trashcan.onclick=函数{deleteImage'+image.id+'';};另外,如果图像是一个img标记,那么您不能有孩子。您可以提供一个JSFIDLE吗?图像显示在3个分区中:1个容器,一个图像预览,它是一个img标记,另一个分区显示图像名称。de container是实际创建子级的div,因此不会导致问题。我添加了一个指向实际文件的链接,这可能会更好?我无法访问脚本/html,因此无法使用它:PI不认为他在使用jQuery。如果没有理由他不能使用它,为什么不使用它:PI认为链接到网站本身会更好。这是因为图像采集器通过xmlhttprequests从这些图像所在的文件夹中的API加载所有图像。这通常不会由JSFIDLE加载。尽管如此,这里是:不需要图像:D,你没有评论答案,你在上面评论了我的评论,你可以使用jquery吗?我可以,但我更喜欢继续使用纯javascript,因为我的整个项目都在使用它,我在jquery方面没有经验