[英]Change content of textarea with jquery/javascript
I am using gridster widgets on my webpage.Each widgets have multiple images on it and a textarea.The textarea contains the links of image seperated by comma.The initial content of textarea is achieved from JSON.The images can be deleted from the grid.I want to update the content of text area as the images are deleted from the grid.(If I delete and image the link of that image from text area should go away).As of now I am getting a static content in the textarea. 我在网页上使用gridster小部件,每个小部件上都有多个图像和一个textarea.textarea包含以逗号分隔的图像链接.textarea的初始内容是通过JSON实现的,可以从网格中删除图像。我想更新文本区域的内容,因为图像已从网格中删除。(如果删除并成像,则该文本从文本区域的链接应该消失了)。到目前为止,我在文本区域中获得了静态内容。
My JS to delete the image and an attempt to remove the content of textarea 我的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();
});
But the above code is not capable of making the textarea dynamic.It only works when there is just one image. 但是上面的代码无法使文本区域动态化,仅在只有一张图像时才有效。
My function which generate the widgets 我生成小部件的函数
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);
}
Fiddle will illustrate properly.In Fiddle if you go on deleting the image the text are content remains same.I want it to change. 小提琴将正确地说明。在小提琴中,如果继续删除图像,文本内容将保持不变。我希望更改它。
You should just put the "serialize" code in a function and call that function whenever an element is deleted: 您应该只将“序列化”代码放入函数中,并在删除元素时调用该函数:
$('.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.