2017-06-01 65 views
0

想象一下,你有這樣的標記:添加目標和rel用PHP

原始代碼:

<p class="Add"> 
    <a href="https://google.com">Google</a> 
    <a href="https://google.com">Google</a> 
    <a href="https://google.com">Google</a> 
    <a href="https://google.com">Google</a> 
</p> 

所需的代碼:

<p class="Add"> 
    <a href="https://google.com" target="_blank" rel="noFollow noReferrer" class="l">Google</a> 
    <a href="https://google.com" target="_blank" rel="noFollow noReferrer" class="l">Google</a> 
    <a href="https://google.com" target="_blank" rel="noFollow noReferrer" class="l">Google</a> 
    <a href="https://google.com" target="_blank" rel="noFollow noReferrer" class="l">Google</a> 
</p> 

瞄準 「P」 與類的 「添加」 ,我如何用php添加:

  • 「target」屬性全部嵌套元素
  • 的「相對」屬性的所有嵌套元素
  • 類「L」到所有嵌套元素

我需要動態改變HTML結構,原始鏈接由一構成模塊,並且我無法在構建原始html之前更改它們。在我用javascript做這件事之前,js不是一種選擇,因爲有些用戶沒有在瀏覽器中啓用js。

我以前的js代碼是:

$(".Add a").attr("target", "_blank"); 
$(".Add a").attr("rel", "noFollow noReferrer"); 
$(".Add a").addClass("l"); 

謝謝。

+0

想要在PHP中動態生成這些鏈接?你是如何製作原稿的? – WillardSolutions

+1

是的EatPeanutButter,我需要動態地改變它們。對不起,我忘記了這一點。原始鏈接是由模塊構建的,我無法在構建此html之前更改它們。在我用javascript來做之前,但js不是一種選擇,因爲有些用戶在瀏覽器中沒有啓用js。 – Cell

+0

如果你提到你如何調用創建鏈接的「模塊」,這將是一件好事。 –

回答

0

這是你在找什麼?你可以做到這一點,只有在滿足某些條件時纔打印。

<p class="Add"> 
    <a href='https://google.com' <?php echo("target='_blank'") ?> <?php echo("rel='noFollow noReferrer'") ?> <?php echo("class='l'") ?>>Google</a> 
    <a href='https://google.com' <?php echo("target='_blank'") ?> <?php echo("rel='noFollow noReferrer'") ?> <?php echo("class='l'") ?>>Google</a> 
    <a href='https://google.com' <?php echo("target='_blank'") ?> <?php echo("rel='noFollow noReferrer'") ?> <?php echo("class='l'") ?>>Google</a> 
    <a href='https://google.com' <?php echo("target='_blank'") ?> <?php echo("rel='noFollow noReferrer'") ?> <?php echo("class='l'") ?>>Google</a> 
</p> 
+0

感謝您的回答克里斯,但我需要動態地改變它們。對不起,我忘了提及這一點。原始鏈接是由模塊構建的,我無法在構建此html之前更改它們。我編輯了我的問題以更好地解釋它。謝謝。 – Cell

+0

爲什麼不在頁面加載後只使用Javascript來添加這些屬性?你可以遍歷這個例如document.getElementsByClassName(「add」)[0] .setAttribute(「target」,「_blank」); –

+1

因爲如果javascript被禁用,它將不起作用。 – Cell