html
<button onclick="myFunction()">Go</button>
<button onclick="removeone()">
Remove
</button>
Javascript
這讓我可以在 iframe 視窗中訪問任何網站
function myFunction() {
let userdata= prompt("Enter site name", "http://");
if (userdata != null) {
const ifrm = document.createElement("iframe");
ifrm.setAttribute("src", userdata);
ifrm.style.width = "1620px";
ifrm.style.height = "880px";
document.body.appendChild(ifrm);
} else {}
}
這將洗掉 iFrame
function removeone() {
const iframe = document.querySelector('iframe')
iframe.remove()`
我的問題是每當我洗掉 iframe 時,它??首先洗掉最舊的元素,而不是我想要的新創建的元素。我是 JavaScript 編程新手。
uj5u.com熱心網友回復:
細節在例子中注釋
// Bind "click" event to <button>
document.querySelector(".open").onclick = openIframe;
// Event handler passes event object by default
function openIframe(event) {
// Prompt user for url
let url = prompt("Enter site name", "https://");
// If url isn't null...
if (url != null) {
// Create <iframe> and <button>
const ifrm = document.createElement("iframe");
const btn = document.createElement("button");
// Add attributes and styles to both elements
ifrm.src = url;
ifrm.style.display = "block";
ifrm.style.width = "98%";
ifrm.style.minHeight = "100vh";
btn.style.display = "block";
btn.textContent = "Remove";
// Append <button> then <iframe> to <body>
document.body.append(btn, ifrm);
// Bind "click" event to <button>
btn.onclick = function(event) {
// Find the element that follows <button> (ie <iframe>) and remove it
this.nextElementSibling.remove();
// <button> removes itself
this.remove();
}
}
}
<button class="open">GO!</button>
uj5u.com熱心網友回復:
嘗試
function removeone() {
const n = document.querySelectorAll('iframe').length;
const iframe = document.querySelectorAll('iframe')[n-1];
iframe.remove();
}
解釋
來自官方檔案
Document 方法 querySelector() 回傳檔案中與指定選擇器或選擇器組匹配的第一個元素。如果沒有找到匹配項,則回傳 null。
因此,您可以使用querySelectorAll. 也來自官方檔案
Document 方法 querySelectorAll() 回傳一個靜態(非實時)NodeList,表示與指定選擇器組匹配的檔案元素串列
因此,您只需抓住該 NodeList 的最后一個元素并將其洗掉。您可以像在 Javascript 中的常規陣列中一樣獲取 NodeList 中的最后一個元素。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/511118.html
