![](/img/trans.png)
[英]How to change the Content of a <textarea> with JavaScript
[英]Change content of textarea with jquery/javascript
我在網頁上使用gridster小部件,每個小部件上都有多個圖像和一個textarea.textarea包含以逗號分隔的圖像鏈接.textarea的初始內容是通過JSON實現的,可以從網格中刪除圖像。我想更新文本區域的內容,因為圖像已從網格中刪除。(如果刪除並成像,則該文本從文本區域的鏈接應該消失了)。到目前為止,我在文本區域中獲得了靜態內容。
我的JS刪除圖片並嘗試刪除textarea的內容
$('.removediv').on('click', function () {
var textArea = $(this).parent().next();
var text = textArea.val();
var imgSrc = $(this).prev().attr("src");
textArea.val(text.replace(imgSrc, ""));
$(this).closest('div.imagewrap').remove();
});
但是上面的代碼無法使文本區域動態化,僅在只有一張圖像時才有效。
我生成小部件的函數
for(var index=0;index<json.length;index++) {
var images = json[index].html.split(',');
var imageOutput = "";
for(var j = 0; j < images.length; j++) {
imageOutput += '<div class="imagewrap"><img src='+ images[j] +'> <input type="button" class="removediv" value="X" /></div></div>';
}
gridster.add_widget('<li class="new" ><button class="delete-widget-button" style="float: right;">-</button>' + imageOutput + '<textarea>'+json[index].html+'</textarea></li>',json[index].size_x,json[index].size_y,json[index].col,json[index].row);
}
小提琴將正確地說明。在小提琴中,如果繼續刪除圖像,文本內容將保持不變。我希望更改它。
您應該只將“序列化”代碼放入函數中,並在刪除元素時調用該函數:
$('.removediv').on('click', function() {
var textArea = $(this).parent().next();
var text = textArea.val();
var imgSrc = $(this).prev().attr("src");
textArea.val(text.replace(imgSrc, ""));
$(this).closest('div.imagewrap').remove();
serialize();
});
$('.js-seralize').on('click', function() {
serialize();
});
function serialize(){
var s = gridster.serialize();
$('.gridster ul li').each((idx, el) => { // grab the grid elements
s[idx].html = $('textarea', el).html(); // add the html key/values
json_variable = JSON.stringify(s)
});
$('#log').val(json_variable);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.