gpt4 book ai didi

javascript - 替换点击时动态生成的图像

转载 作者:行者123 更新时间:2023-11-28 18:46:48 24 4
gpt4 key购买 nike

如何替换循环生成的动态图像?

enter image description here

上面的图像在由 mustache 模板系统渲染的 html 中应如下所示。

{{#images}}

<div class="picture-caption">
<img id="{{id}}" class="caption" src="./data/picture_caption/{{picture_caption}}" alt="your image" />
<input id="image-value" data-id="{{id}}" class="image-box-{{id}}" type="file" style="display: none;" value="
{{picture_caption}}" />{{id}}
</div>

{{/answers}}

我进行了编码并计算出仅更改循环中的第一个索引(这是儿子 guko 图像)

function readURL(input, caption_id) {
if (input.files && input.files[0]) {
var reader = new FileReader();

reader.onload = function (e) {
$("#"+caption_id).attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}

$(".caption").click(function(e) {
var caption_id = $(this).attr('id');
// console.log(caption_id);
$(".image-box-"+caption_id).click();
});

$("#image-value").change(function(e){
var caption_id = $(this).attr('data-id');
// alert(caption_id);
readURL(this, caption_id);
});

我可以采取任何想法/替代方案来实现这一点吗?

最佳答案

您有多个具有相同 id (id="image-value") 的输入元素,这就是为什么 jQuery 在执行您在此处绑定(bind)的 onchange 处理程序时仅选取其中第一个的原因 - $( "#image-value").change(function(e){...}).

因此将 $("#image-value").change(function(e){...}) 替换为 $('[type="file"]') .change(function(e){...}) 如下所示,将事件处理程序附加到所有输入元素。

查看演示 - Fiddle .

function readURL(input, caption_id) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$("#"+caption_id).attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}

$(".caption").click(function() {
$(".image-box-"+this.id).click();
});

$('[type="file"]').change(function(e){
var caption_id = $(this).attr('data-id');
readURL(this, caption_id);
});

您可以使用类选择器来代替[type="file"]。为此,您可以:

  1. 向所有输入添加一个额外的类,例如 class="image-box-{{id}} your-class",然后像 $('.your-class' 一样使用它).change(function(e){...})

  • 也许只是缩短你必须的 class="image-box" ,因为没有理由将单独的类附加到每个元素,并像 $('. image-box').change(function(e){...}).
  • 我会删除每个元素重复的 id="image-value" 以避免将来出现潜在错误或更改为 id="image-value-{{id}} “

    关于javascript - 替换点击时动态生成的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35192244/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com