簡體   English   中英

使用jQuery動態地將缺少的alt應用於圖像,在w3c驗證中顯示類似“圖像必須具有alt屬性”的錯誤

[英]Dynamically applying missing alt to the image using jQuery showing error like “image must have an alt attribute” in w3c validation

我使用以下代碼在w3c驗證時遇到錯誤。

<div class="media">
  <div class="pull-left">
    <img class="img-responsive" src="http://10.70.2.81/resource/images/Trustworthy-Guidance.png" >
  </div>
  <div class="media-body">
    <h4 class="media-heading text-align-left">Trustworthy Guidance</h4>
    <p class="text-align-left font-family-light">With up-to-date knowledge of various technology platforms and programming languages, we have the expertise to guide you to the right software solution for your business.</p>
  </div>
</div>

我添加了以下代碼,用於使用jQuery動態地將缺少的alt應用於圖像:

$(document).ready(function() {
    $('img').each(function() {
        var $img = $(this);
        var filename = $img.attr('src').replace(new RegExp("-", "g"), ' ');
        var filename1 = filename.substring(filename.lastIndexOf('/')+1);    
        var attr = $(this).attr('alt');
        var title = $(this).attr('title');    

        if (typeof attr == typeof undefined || attr == false) {
            $img.attr('alt', filename1.substring(0, filename1.indexOf('.')));
        }
    });
});

即使我得到相同的錯誤,像image must have an alt attribute在w3c驗證中image must have an alt attribute 如何使用jQuery避免該錯誤,否則我需要在所有頁面中手動編輯。

您無法使用JavaScript將圖像alt屬性( 兩者都沒有 )設置為文檔,從而成為有效的HTML輸出!

w3c驗證,僵屍程序或抓取工具等服務不會執行JavaScript代碼。 因此,根據您的頁面請求,您的HTML完全錯誤並且缺少這些信息。 瀏覽器可以執行您的JavaScript代碼並將正確的信息添加到DOM元素。 對於使用通用瀏覽器的用戶來說,一切似乎都很好,但對於任何自動化系統,它都不是。

因此,在頁面加載后,使用JavaScript動態地執行此類操作通常是一個壞主意,因為搜索引擎無法正確收集數據。 圖像alt是搜索引擎的重要屬性,他們無法在您的示例中讀取此信息。

如果你想擁有一個最友好的SEO頁面,你應該根據要求提供正確的HTML,而不是之后操縱內容!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM