首頁  >  文章  >  web前端  >  如何在 JavaScript 中透過超連結定位特定框架?

如何在 JavaScript 中透過超連結定位特定框架?

WBOY
WBOY轉載
2023-09-08 14:01:09818瀏覽

如何在 JavaScript 中通过超链接定位特定框架?

HTML 框架提供了將瀏覽器視窗分割為多個部分的便捷方法。

其中每個部分都可以載入單獨的 HTML 文件。我們可以使用 JavaScript 將內容載入到特定的框架中,使用視窗物件的框架屬性。 Frames 屬性是一個類似陣列的對象,包含目前頁面上的所有框架(包括 iframe)。

我們可以透過多種方式使用 window.frames[] 屬性將文件的內容載入到框架中。讓我們一一看看它們 -

1。使用索引

要定位特定框架,您可以使用框架的索引或名稱。例如,要定位頁面上的第一幀,您可以使用以下程式碼 -

window.frames[0].document.location.href = "http://www.example.com"

2。使用框架名稱

要使用其名稱來定位框架,可以使用下列方法。假設框架的名稱是“frame_name” -

window.frames["frame_name"].document.location.href = "http://www.example.com";

3。使用 getElementById 和 getElementByName

您也可以使用 getElementById() 或 getElementsByName() 方法定位框架,然後使用方法 contentWindow 存取框架窗口,如下所示 -

document.getElementById("frame_id").contentWindow.location.href = "http://www.example.com";
document.getElementsByName("frame_name")[0].contentWindow.location.href = "http://www.example.com";

範例

以下是包含所有這些方法的完整工作程式碼片段 -

<!DOCTYPE html>
<html>
<head>
   <title>Target a frame</title>
</head>
<body>
   <button onclick="indexMethod()">Using Index</button>
   <button onclick="nameMethod()">Using Frame Name</button>
   <button onclick="queryMethod()">Using Query Methods</button>
   <iframe src=""
      height="150px"
      width="100%"
      name="frame_name"
      id="frame_id" srcdoc="<html>
         <body style='background-color:#ccc;'>
         <h1>Testing iframe</h1>
         </body>
         </html>">
   </iframe>
   </body>
   <script>
      const indexMethod = () => {
         const child = document.createElement('p');
         child.innerText = 'added inside frame';
         window.frames[0].document.body.appendChild(child);
     };
      const nameMethod = () => {
         const child = document.createElement('p');
         child.innerText = 'added inside frame';
         window.frames["frame_name"].document.body.appendChild(child);
     };
     const queryMethod = () => {
         const child = document.createElement('p');
         child.innerText = 'added inside frame';
         document.getElementById("frame_id").contentWindow.document.body.appendChild(child);
     };
   </script>
</html>

以上是如何在 JavaScript 中透過超連結定位特定框架?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除