问题描述
两个tr 上面的tr里面是图片信息,有多个。。用jquery动态添加的,下面tr里的button也是,动态添加的多个,怎么点其中的一个button remove掉相对于的图片? 问题补充:if(data[0].picList.length>0){ var count =0; $('#img1').attr('src',data[0].picList[0]); if(data[0].picList.length>1){ for(var i=1;i<data[0].picList.length;i++){ $('#img1').after("<img width='100px' height='100px' name='imgs' id ='imgs'/>"); $('#delImg').after("<input type='button' id='delImg' style='margin-left:50px' onclick='delImgs(this)' value='删除' />");$('#imgs').attr('src',data[0].picList[i]);} }}这个是创建img 和 button
解决方案
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%><%String path = request.getContextPath();%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Insert title here</title><script type="text/javascript" src="<%=path %>/javascript/jquery-2.0.3.js"></script><script type="text/javascript">var image1 = 'http://pic2.sc.chinaz.com/Files/pic/icons128/5635/103.png';var image2 = 'http://pic1.sc.chinaz.com/Files/pic/icons128/5635/113.png';var image3 = 'http://pic1.sc.chinaz.com/Files/pic/icons128/5635/123.png';var image4 = 'http://pic1.sc.chinaz.com/Files/pic/icons128/5635/13.png';var image5 = 'http://pic1.sc.chinaz.com/Files/pic/icons128/5635/133.png';var imageArr = [image1,image2,image3,image4,image5];function createImagesAndRemoveButtons() {for(var i = 0;i < imageArr.length;i++) {var imageId = 'createImage' + i;var buttonId = 'createButton' + i;$('#initializableIMG').append("<img width='100px' height='100px' name='imgs' id ='" + imageId + "' src='" + imageArr[i] + "'/>");$('#removeButtons').append("<input type='button' id='delImg' style='margin-left:50px' onclick='delImgs("" + imageId + "",this)' value='删除' />"); }}function delImgs(imageId,button) {$('#' + imageId).remove();$(button).remove();}$(function(){createImagesAndRemoveButtons();});</script></head><body><table width="80%"><tr width="100%"><td>信息图片</td><td id="initializableIMG"></td></tr><tr><td></td><td id="removeButtons"></td></tr></table></body></html>
解决方案二:
设计有问题,id必须是唯一的。定义个全局变量num=1,每次动态添加图片时,给img的id设为img+num,button的onclick事件里直接onclick='delImgs(num)',然后根据num拼装成要删除的img的id,$("#img"+num).每次添加之后num+1