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

jQuery点击img取alt赋值span报undefined,如何实现还原及hover适配

修复方案

方案1:最小改动现有代码

修改HTML中img的onclick属性,把当前点击元素作为参数传入函数:

<span class='item__info'>original text</span>

<div class='gallery'>
    <img src='image source 1'
         onclick='showInfo(this)' alt='123412341' class='gallery__item'>
    <img src='image source 2'
         onclick='showInfo(this)' alt='testing' class='gallery__item'>
</div>

调整JS逻辑接收传入的元素参数:

function showInfo(img) {
    let alt = $(img).attr('alt');
    $('.item__info').text(alt);
}

方案2:移除行内事件(更推荐,避免HTML和JS逻辑耦合)

删掉所有img标签里的onclick属性,直接用jQuery绑定事件:

// 提前存储span初始文本,后续还原会用到
const originalText = $('.item__info').text();

$('.gallery__item').on('click', function() {
    // 此时this指向触发点击的img元素,可正常读取alt属性
    let alt = $(this).attr('alt');
    $('.item__info').text(alt);
});

附加问题解答

1. 点击图片以外区域还原span初始值

在方案2的基础上新增全局点击事件,同时阻止图片点击事件冒泡即可:

const originalText = $('.item__info').text();

$('.gallery__item').on('click', function(e) {
    // 阻止事件冒泡到document,避免刚赋值就被还原
    e.stopPropagation();
    let alt = $(this).attr('alt');
    $('.item__info').text(alt);
});

// 点击任意非图片区域触发还原
$(document).on('click', function() {
    $('.item__info').text(originalText);
});

2. 触发事件改为hover是否可以正常实现

可以正常实现,hover是jQuery封装的mouseenter(鼠标移入)和mouseleave(鼠标移出)组合事件,调整对应逻辑即可:

const originalText = $('.item__info').text();

$('.gallery__item').hover(
    // 鼠标移入图片时显示对应alt
    function() {
        let alt = $(this).attr('alt');
        $('.item__info').text(alt);
    },
    // 鼠标移出图片时自动还原初始文本
    function() {
        $('.item__info').text(originalText);
    }
);

该场景下不需要额外绑定全局点击事件,鼠标移出图片就会自动还原内容。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 22:06:04