You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET C#中jQuery页面加载时动态加载图片的循环问题求助

问题:通过jQuery动态为img标签批量设置属性失败

我是JavaScript和jQuery新手,希望在页面加载时通过jQuery为页面内的img标签动态设置alt、title、src属性。已构建如下HTML结构:

<div>
 <ul>
<li>
 <a data-title="Call Long 1">
<em><img class="img-responsive" alt="" title="" src="" /></em>
<span>Image 1</span></a>
</li>
<li>
 <a data-title="Call Long 2">
<em><img class="img-responsive" alt="" title="" src="" /></em>
<span>Image 2</span></a>
</li>
</ul>
</div>

并通过AJAX调用ASP.NET的WebMethod(AutoTrade.aspx/LoadServiceImages)获取图片数据,但尝试多种each、for循环赋值逻辑均失效,相关JS代码如下:

function LoadImages() {


    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        //url is the path of our web method (Page name/function name)
        url: "AutoTrade.aspx/LoadServiceImages",
        data: "{}",
        dataType: "json",
        //called on jquery ajax call success
        success: function (result) {

            $.each(result.d, function (key, value) {

                //$(".img-responsive").each(function () {
                //    $(this).attr('src', value.ImageURL).attr('title', value.Toltip).attr('alt', value.StrategyName);
                //});

                 $(".img-responsive").attr('src', value.ImageURL).attr('title', value.Toltip).attr('alt', value.StrategyName);

            });


            //$(".img-responsive").each(result.d, function (key, value) {

            //    $(this).attr('src', value.ImageURL).attr('title', value.Toltip).attr('alt', value.StrategyName);

            //});


            //for (var imgcount = 0; imgcount < result.d.length; imgcount++) {

            //    //alert('hit');
            //    //alert(result.d[i].Toltip)
            //    $(".img-responsive").attr('src', result.d[imgcount].ImageURL).attr('title', result.d[imgcount].Toltip).attr('alt', result.d[imgcount].StrategyName);
            //}



            //$(".img-responsive").each(result.d, function (key, value) {

            //    //alert(value.Toltip);

            //    $(".img-responsive").attr('src', value.ImageURL).attr('title', value.Toltip).attr('alt', value.StrategyName);

            //    //alert(value.Toltip);
            //});



            //$(".img-responsive").each(result.d, function () {

            //    //alert(value.Toltip);

            //    $(".img-responsive").attr('src', result.d[0].ImageURL).attr('title', result.d[0].Toltip).attr('alt', result.d[0].StrategyName);

            //    //alert(value.Toltip);
            //});



            //alert(result.d.length);
            //$(document).ready(function () {

            //    for (var i = 0; i < result.d.length; i++) {

            //        alert(value.Toltip);
            //        $(".img-responsive").attr('src', result.d[i].ImageURL).attr('title', result.d[i].Toltip).attr('alt', result.d[i].StrategyName);
            //        alert(value.Toltip);
            //    }

            //});


        },

        //called on jquery ajax call failure
        error: function ajaxError(result) {
            alert(result.status + ' : ' + result.statusText);
        }
    });

}

解决方案

之前的代码核心问题是:每次循环都选中所有.img-responsive元素赋值,最终所有img都会被覆盖成最后一条数据的属性值。需要将数据项和对应的img元素一一对应,以下是两种可行的写法:

方法一:遍历img元素,按索引匹配数据

success: function (result) {
    // 提前获取所有目标img元素,避免重复DOM查询
    const $imgs = $(".img-responsive");
    // 遍历每个img,index为当前元素的索引
    $imgs.each(function(index) {
        // 防止数据数量与img数量不一致导致报错
        if (index < result.d.length) {
            const dataItem = result.d[index];
            // 用对象参数一次性设置多个属性,更简洁
            $(this).attr({
                'src': dataItem.ImageURL,
                'title': dataItem.Toltip,
                'alt': dataItem.StrategyName
            });
        }
    });
}

方法二:遍历数据数组,按索引匹配img元素

success: function (result) {
    const $imgs = $(".img-responsive");
    // 遍历返回的数据数组
    $.each(result.d, function(index, dataItem) {
        // 确保索引不超出img元素的数量
        if (index < $imgs.length) {
            // 通过eq(index)获取对应位置的img元素
            $imgs.eq(index).attr({
                'src': dataItem.ImageURL,
                'title': dataItem.Toltip,
                'alt': dataItem.StrategyName
            });
        }
    });
}

关键说明

  • 提前缓存$imgs集合,减少DOM查询次数,提升性能
  • 通过index(索引)建立数据与img的一一对应关系
  • 使用attr()的对象参数写法,比多次调用attr()更高效简洁
  • 增加索引判断,避免数据和img数量不匹配时出现越界错误

内容的提问来源于stack exchange,提问作者Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 15:35:36