我正在使用 Gridster 作为网页。小部件上有图像。可以使用 +
添加和删除这些图像。和X
按钮。
有两个<textarea>
小部件上的字段。
一个与
class="hoverinformation" \\ it captures title attribute for image
以及其他
class="imagenames"\\it captures image src.
我编写了一段代码,用于在删除或添加图像时动态更新文本区域。
编写的代码输出存在问题
- 当我删除图像时
src
和title
被删除但不必要,
还剩 - 当我手动添加图像时
<textarea>
已更新,但当我删除该图像时,该图像仅<textarea>
与class="imagenames"
得到更新。<textarea>
与class="hoverinformation "
没有更新。 - 当我删除从
JSON
生成的所有图像时(当用户加载页面时最初出现),然后如果我手动添加图像,那么<textarea>
不更新 (当我 checkininspect element
时,两个textarea
都会动态更新)
我的删除图像和更新文本区域的代码
$(document).on('click', '.removediv', function () {
//For textarea with class 'imagenames'
var imagename = $(this).parent().siblings('.imagenames');
var text = imagename.val();
var imgSrc = $(this).prev().attr("src");
imagename.val(text.replace(imgSrc, ""));
//For textarea with class 'hoverinformation'
var hoverinformation = $(this).parent().siblings('.hoverinformation');
var text = hoverinformation.val();
var title = $(this).prev().attr("title");
hoverinformation.val(text.replace(title,""));
$(this).closest('div.imagewrap').remove();
});
我的代码手动添加图像并更新<textarea>
var parentLI;
$(document).on("click", ".addmorebrands", function() {
parentLI = $(this).closest('li');
$('#exampleModalCenter').modal('show');
$('#exampleModalCenter img').click(function(){
$(this).addClass('preselect');
$(this).siblings().removeClass('preselect');
selectedImageSRC = $(this).attr('src');
})
});
$('#add-image').click(function(){
parentLI.append('<div class="imagewrap"><img class="images" src="'+selectedImageSRC+'" title="Manual Addition"> <input type="button" class="removediv" value="X" /></div>');
parentLI.children('.imagenames').append(', '+selectedImageSRC);
parentLI.children('.hoverinformation').append(', '+"Manual Addition");
$('#exampleModalCenter').modal('hide');
});
我不明白为什么会出现如此奇怪的行为。任何帮助都会很棒。
最佳答案
这样你就可以摆脱“,”
$(document).on('click', '.removediv', function () {
var imagename = $(this).parent().siblings('.imagenames');
var text = imagename.val();
var imgSrc = $(this).prev().attr("src");
text = removestring(text, imgSrc);
imagename.val(text);
var hoverinformation = $(this).parent().siblings('.hoverinformation');
var text = hoverinformation.val();
var title = $(this).prev().attr("title");
text = removestring(text, title);
hoverinformation.val(text);
$(this).closest('div.imagewrap').remove();
});
function removestring(text, title) {
var arr = text.split(",");
var index = arr.indexOf(title);
if (index > -1) {
arr.splice(index, 1);
}
text = arr.join(",");
return text;
}
关于javascript - 文本区域内容未使用 JS/jquery 动态更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49521654/