我正在嘗試編輯帖子。但我有一些問題。JQuery單擊編輯帖子和選定的ID不起作用
我從codepen.io創建了這個DEMO。
在這個演示中你可以看到有兩個編輯按鈕(red)
。當你點擊第一個編輯按鈕時,文本和圖像編輯區將會出現在那裏。但是,如果您檢查開發者控制檯,您可以看到圖像ID不是真實圖像ids。像正常的第一個圖像id="1"
和第二個圖像id="2"
,但點擊編輯按鈕後,編輯區域圖像ID不是第二個圖像id="2"
所有圖像id="1"
我的jQuery代碼中有什麼問題。
此外,我怎麼可以把圖片ID從<div class="del" id="here">x</div>
HTML
<div class="container">
<div class="postAr" id="messageB1">
<div class="postInfo">
<img src="http://hdwallpaperia.com/wp-content/uploads/2013/10/Home-Sweet-Home-Wallpaper.jpg" class="ab" id="1">
</div>
<div class="postInfo">
<img src="http://hdwallpaperia.com/wp-content/uploads/2013/10/Home-Sweet-Home-Wallpaper.jpg" class="ab" id="2">
</div>
<div class="ptx"> fdasfads fsasd fadsf adsf adsf adsf asd fasd f dfsas</div>
<div class="editBtn" name="edit" id="1">Edit1</div>
</div>
</div>
<div class="container">
<div class="postAr" id="messageB2">
<div class="postInfo">
<img src="http://cdn.theatlantic.com/assets/media/img/photo/2015/11/images-from-the-2016-sony-world-pho/s01_130921474920553591/main_900.jpg?1448476701" class="ab" id="2">
fdasfads fasd fadsf aldsf adsf adsf asd fasd f dfsassssg5
</div>
<div class="ptx"> fdasfads fasd fadsf adsf adsf adsf asd fasd f dfsas</div>
<div class="editBtn" name="edit" id="2">Edit2</div>
</div>
</div>
JS
$(document).ready(function() {
$("body").on("click", ".editBtn", function(event) {
event.target.disabled = true;
var ID = $(this).attr("id");
var selected = $("#messageB" + ID + " .postInfo img").parent().html();
var currentMessage = $("#messageB" + ID + " .ptx").html();
var imid = $(".postInfo img").attr("id");
var editImage = $('<div class="edi"><div class="del" id="imageid">x</div>' + selected + '</div>').html();
var editMarkUp = '<div class="edBtnS"><div class="edSv">Save</div><div class="cNeD" id="' + ID + '">Cancel</div></div><textarea rows="5" cols="80" id="txtmessage_' + ID + '">' + currentMessage + '</textarea>';
$("#messageB" + ID + " .ptx").html(editMarkUp);
$("#messageB" + ID + " .postInfo").html(editImage);
var data = $('#txtmessage_' + ID).val();
$('#txtmessage_' + ID).focus();
$('#txtmessage_' + ID).val(data + ' ');
});
$("body").on("click", ".cNeD", function(event) {
$(".editBtn").prop('disabled', false);
var ID = $(this).attr("id");
var currentMessageText = $("#txtmessage_" + ID).html();
$("#messageB" + ID + " .ptx").html(currentMessageText);
});
});
首先你不能多次使用相同的id值; id =「2」 – itzmukeshy7
@ itzmukeshy7是的,我知道親愛的。我想知道我該怎麼做。我需要幫助。 – Azzo
這是因爲您正在使用的選擇器返回第一個元素ID,即1 – itzmukeshy7