亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在JavaScript中獲取頁面語言(hreflang)并將其作為參數添加到鏈接中

如何在JavaScript中獲取頁面語言(hreflang)并將其作為參數添加到鏈接中

暮色呼如 2022-09-02 10:45:37
例如,我有這個代碼,它能夠將頁面的標題作為參數添加到標識為ID的鏈接中。我希望能夠對頁面的語言做同樣的事情。感謝您的幫助!<script>const linkIds = [  'Your_link_id'];linkIds.forEach(id => {  const interval = setInterval(() => {        const link = document.querySelector('#' + id);    if (link) {      clearInterval(interval);      const href = link.getAttribute('href');      const pageTitle =         document          .title          .replace(/\s+/g, '_')          .replace(/&/g, '')          .toLowerCase()      const newHref = `${href}?your_parameter_name=${pageTitle}`;      link.setAttribute('href', newHref);    }  }, 20);});</script>
查看完整描述

2 回答

?
holdtom

TA貢獻1805條經驗 獲得超10個贊

若要獲取頁面的語言,必須從文檔元素中獲取屬性。我創建了一個示例代碼,用于獲取和設置頁面的語言。您可以將輸出保存到某個變量,并創建與該變量的鏈接。lang


let lang = document.documentElement.lang


console.log(lang)

// output: en


document.documentElement.lang = 'af'


console.log(document.documentElement.lang)


// output: af


查看完整回答
反對 回復 2022-09-02
?
慕容3067478

TA貢獻1773條經驗 獲得超3個贊

我把它作為一個新的答案添加,因為我不確定我應該做什么(這個事實本身表明這不是一個寫得很好的問題),但我會嘗試。


因此,您的腳本使用一些 ID 數組。然后,它為每個 ID 創建一個間隔,該間隔會不斷更新具有該 ID 的元素的屬性,并具有一定值。我不知道為什么你會這樣做,因為或者不會隨著時間的推移而改變,但我可能只是停止問,所以這是編輯過的代碼:hrefpageTitlelanguage


<script>


    const linkIds = [

        'Your_link_id'

    ];


    // here I get the lanugage of the page

    let lang = document.documentElement.lang;


    linkIds.forEach(id => {

        const interval = setInterval(() => {    

            const link = document.querySelector('#' + id);

            if (link) {

                clearInterval(interval);

                const href = link.getAttribute('href');


                // here I set the language where page title was before 

                const newHref = `${href}?your_parameter_name=${lang}`;


                link.setAttribute('href', newHref);

            }

        }, 20);

    });


</script>

嘗試一下并報告。如果你需要使用這樣一個復雜的腳本,那么真正學習Javascript可能對你有好處。


查看完整回答
反對 回復 2022-09-02
  • 2 回答
  • 0 關注
  • 163 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號