我想用dom在图像上嵌入按钮。将有多个图像上有多个按钮,可以在点击时删除图像。
我想要这样的事情 - JSFiddle
我试过的代码:
var div = document.createElement('div');
var parent = document.getElementById('images1');
var btn = document.createElement('input');
btn.type = 'button';
btn.className="multiple",
div.style.cssText = "position: relative; margin-bottom: 10px ; width: 100%;";
btn.style.cssText = " position: absolute; top: 10px; background-image: url(http://totravelistolearn.in/wp-content/themes/travel/images/cross-512.png); width: 20px; height: 20px; border: 0; background-size: 100%; background-repeat: no-repeat;";
//textbox.placeholder = 'Add details about attached Image';
//btn.value = "Remove";
btn.onclick = removeImage;
img = new Image();
img.style.display = 'block';
img.className = 'hi1';
img.style.cssText = 'height: 100px; width: 100px; position: relative;';
img.src = results[i];
div.appendChild(div);
div.appendChild(img);
div.appendChild(btn);
删除图像的功能 -
function removeImage(){
$$(this).prev("img").remove();
$$(this).remove();
div.parentNode.removeChild(div);
}
答案 0 :(得分:1)
您需要使用class
代替id
,closest()
也会为您完成这项工作: DEMO
$('.myButton').click(function(){
$(this).closest('.MyImage').remove();
});
答案 1 :(得分:0)
单击按钮,可以删除包含该图像和按钮的div,如下所示:
$('.myButton').on('click', function() {
$(this).closest('div.MyImage').remove();
});
因为,我不建议在一个页面中的多个元素上使用相同的id
,我已将它们更改为类,然后通过它。如果您的用例允许,我建议您也这样做。
以下是更新的 Fiddle
答案 2 :(得分:0)
据我了解,编写此代码请检查一次。
function createItem() {
div = document.createElement("div");
div.setAttribute("class", "parent");
image = document.createElement("img");
image.src = "http://www.jpl.nasa.gov/spaceimages/images/mediumsize/PIA17011_ip.jpg";
image.style.width = "100%";
btn = document.createElement("button");
btn.setAttribute("class", "MyButton");
var textnode = document.createTextNode("X");
btn.appendChild(textnode);
btn.style.position = "absolute";
btn.style.left = "10px";
btn.style.left = "10px";
div.appendChild(image);
div.appendChild(btn);
div.style.width = "100px";
div.style.height = "100px";
div.style.overflow = "hidden";
div.style.marginBottom = "10px";
document.body.appendChild(div);
}
createItem();
createItem();
createItem();
parentDiv = document.getElementsByClassName("parent");
console.log(parentDiv.length);
buttonObject = document.getElementsByClassName("MyButton");
for (var i = 0; i < buttonObject.length; i++) {
buttonObject[i].id = i;
buttonObject[i].onclick = function() {
myId = this.getAttribute("id");
parentDiv[myId].remove()
}
}