我正在为一个网站写一种相册。用户可以上传图片。当通过 jquery 上传(ajax 调用)上传图像时,服务器将获取一些动态信息:
- 图像路径
- 图片编号
图像 id 将特别用于我需要克隆的对象中的几个地方:
<div class="photoContainer" id=
"photo_clone">
<form ajaxify="/ajax/photos/metadata/save/" class="editablePhoto" id="**PHOTOID**" data-photoid="**PHOTOID**" action="#" method="post" onsubmit="">
<div class="photoWrap editablePhotoReady">
<div class="letterboxedImage photo editablePhotoImage verticallyCentered" style="height:194px;">
<div class="uiScaledImageContainer scaledImage" style="width: 290px; height: 193px; margin-top: -96px;">
<img class="scaledImageFitWidth" src="**PHOTO_URL**" width="288" height="194" alt="">
</div>
</div>
</div>
<div class="inputs">
<div class="captionArea2">
<div class="wrap">
<textarea class="uiTextareaNoResize uiTextareaAutogrow captionTextarea mentionsTextarea textInput DOMControl_placeholder" title="Say something about this photo..." name="caption_text" placeholder="Say something about this photo..." role="textbox" aria-autocomplete="list" autocomplete="off" aria-expanded="false" aria-owns="js_34" onkeydown="" aria-label="Say something about this photo..." style="height: 55px; ">Say something about this photo...</textarea>
</div>
</div>
</div>
<div class="metadataControls">
<div class="inner uiBoxGray"><span data-photo="**PHOTOID**" class="metaIcon deleteIcon"></span><span data-photo="**PHOTOID**" class="metaIcon locationIcon"></span><span class="metaIcon photoState"><i>Pending approval</i></span></div>
</div>
</form>
</div> <!--photo id div-->
如果我要克隆这个对象,是否有某种类型的 jquery 函数可以用来做类似“克隆这个,当你克隆它时,用这个参数映射替换克隆对象中的这些占位符,我将传递给你” . 就像是:
clone(myHtmlToClone, map['imageId': '12345', 'imagePath':'www.domain.com/image/fjeeirefjdf.gif'])
其中 myHtmlToClone 中所有出现的“imageId”都将替换为“12345”,而 imagePath 将替换为“www.domain.com/image/fjeeirefjdf.gif”。这是假设我在 html 中定义了占位符。在上面的 html 代码中,它只是原始的、非动态的 html。
编辑想法:
想法 #1 使用 find(示例取自另一个代码片段,与上述 HTML 标记不匹配)
var clone = $("#my_clone").clone()
clone.find("input[id$=id]")
.attr('id',htmlId + 'id')
.attr('name',htmlId + 'id');
clone.find("input[id$=deleted]")
.attr('id',htmlId + 'deleted')
.attr('name',htmlId + 'deleted');
clone.find("input[id$=new]")
.attr('id',htmlId + 'new')
.attr('name',htmlId + 'new')
.attr('value', 'true');
clone.find("select[id*='favoriteQuestion']")
.attr('id', htmlId + 'favoriteQuestion.id')
.attr('name', htmlId + 'favoriteQuestion.id');
$("#childList").append(clone);
clone.show();
想法2:
var clone = $("#my_clone").clone()
clone.replace('**PHOTOID**', photoId).replace('**PHOTO_URL**', photoUrl);
编辑:工作答案:
function addPhoto(photoId) {
var clone = $("#photo_clone").clone()
clone.find("img[id$=id]")
.attr('id', 'photo_' + photoId)
.attr('name', 'photo_' + photoId);
clone.find('*[data-photoid="clone.id"]')
.attr('data-photoid', photoId);
clone.attr('id', 'photo_' + photoId);
$("#photoList").append(clone);
clone.show();
}