使用带有 id 锚点的 rawurlencode() 时,同一页面链接不起作用


Same page link not working using rawurlencode() with id anchor

编辑:对于其他阅读者,此问题已解决。 锚点 ID 中不允许使用 %20。

使用锚 ID 的通常原因,我正在制作一个文本链接列表作为标题,这些标题只是在页面下方链接到每个相关的文本块。

代码有效,没有错误等,除了我无法成功编码 URL。
如果没有rawurlencode()链接就可以正常工作,但是它们有我需要管理的空间(也不会验证)。

我只尝试了 urlencode() 并且工作正常,但它添加了 + 而不是 %20,并且我读到尽可能避免使用 +(也许这不准确,但不能解释为什么rawurlencode()不起作用)。

基本代码:

// The array of list titles
$aryList = array( "1. Communications", "2. Definitions and Conditions");
// Loop to output each list title as a link
foreach ($aryList as $strListValue)
  {
    echo "<a href='#".rawurlencode($strListValue)."'>$strListValue</a>";
  }
// The content with the list title as the link ID (destination)
echo "<a id='".rawurlencode($aryList[0])."'>".$aryList[0]."</a>";
echo "The text is about Communications.";

在源代码中,我可以看到rawurlencode()用 %20 替换空格,尽管浏览器地址栏中的 URL 没有 %20 而是用空格代替。单击链接不会执行任何操作。

使用rawurlencode()时的源代码:

// The list title links
<a href='#1.%20Communications'>1. Communications</a>
<a href='#2.%20Definitions%20and%20Conditions'>2. Definitions and Conditions</a>
// The list IDs (destination)
<a id='1.%20Communications'>1. Communications</a>
<a id='2.%20Definitions%20and%20Conditions'>2. Definitions and Conditions</a>

浏览器是冰鼬 17.0.9 FWIW。

编辑:
根据 durrrutti 所说的内容进行测试,当我只rawurlencode()锚点而不是 ID 时,它工作得很好。

但是,这仍然会在ID中留下空格的问题。

源代码现在只编码了锚点,而不是 ID:

// The list title links
<a href='#1.%20Communications'>1. Communications</a>
<a href='#2.%20Definitions%20and%20Conditions'>2. Definitions and Conditions</a>
// The list IDs (destination)
<a id='1. Communications'>1. Communications</a>
<a id='2. Definitions and Conditions'>2. Definitions and Conditions</a>

元素 ID 不能以字母字符以外的任何内容开头,即 A-Z 和 a-z。我认为这是你的问题。

更新:此外,ID 不能包含百分号。