【问题标题】:php: Echo "alt tag" contents to "title tag"php:将“alt tag”内容回显到“title tag”
【发布时间】:2018-04-29 06:53:29
【问题描述】:

PHP 文件中的图像有一个“alt”标签,但我需要将其内容复制到“title”标签。因此代码在加载时会自动读取页面,并在“alt”标签旁边添加新的“title”标签,无论是使用 PHP、jQuery、JavaScript..

例子:

<img border="0" src="../../../../images/divider.jpg" alt="description of image" width="410" height="15">

输出:

<img border="0" src="../../../../images/divider.jpg" alt="description of image" title="description of image" width="410" height="15">

【问题讨论】:

    标签: php jquery html tags alt


    【解决方案1】:

    使用JavaScript,可以搜索&lt;img&gt;标签,并添加这个title属性:

    let imgs = document.querySelectorAll('img');
    for (let i=0;i<imgs.length;i++) {
      if (!imgs[i].title) // if title is not defined
          imgs[i].title = imgs[i].alt;
    }
    

    使用 jQuery,您可以使用 $('img') 查找图像并使用 each() 循环:

    $('img').each(function(img) {
      if (!this.title)
        this.title = this.alt;
    });
    

    【讨论】:

    • 谢谢..我试过了,但不能让它工作..你能在jsfiddle.net做一个演示吗?
    • @Mike see jsfiddle.net/u3hfkxg9 您应该检查图像标签以查看标题属性。
    • 或者 jsfiddle.net/u3hfkxg9/1 使用 jQuery,jsfiddle.net/u3hfkxg9/2 使用 DOMReady。
    • 它成功了,谢谢.. 但是为什么当我查看页面的源代码时它没有显示新标签?
    • 源代码向您展示了服务器生成的 HTML。使用 JavaScript,DOM 在客户端更新。因此,它只能在浏览器检查器上查看。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-29
    • 2012-08-12
    相关资源
    最近更新 更多