【问题标题】:insert img alt text into span on click单击时将 img alt 文本插入 span
【发布时间】:2021-11-21 00:33:04
【问题描述】:

目标是用 img 的 alt 属性更改 span 的文本,但到目前为止输出是 undefined

html:

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

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

jquery:

function showInfo() {
    let alt = $(this).attr('alt');
    $('.item__info').text(alt); //output: undefined
}

当时:

  • 点击离开图片后,如何将文本恢复为原始文本?
  • 这是否适用于悬停而不是点击?

非常感谢!

【问题讨论】:

    标签: javascript html jquery css


    【解决方案1】:

    调用函数时传递this作为参数。

    function showInfo(elem) {
        let alt = $(elem).attr('alt');
        $('.item__info').text(alt); //output: undefined
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-07
      • 2013-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多