我想創(chuàng)建一個(gè)網(wǎng)頁(yè),作為一個(gè)有趣的項(xiàng)目來(lái)創(chuàng)造迷因。
到目前為止,我正在嘗試通過(guò)JS使用url向文檔主體添加一個(gè)新的圖像元素,該url被輸入到具有URL輸入類型的標(biāo)簽中,但是圖像似乎無(wú)法加載
//通過(guò)下面的代碼,我期望在將圖像元素附加到dom后,url的實(shí)際圖像會(huì)出現(xiàn)在網(wǎng)頁(yè)上,但情況似乎并非如此
const form = document.querySelector('#form');
form.addEventListener('submit', function (e) {
e.preventDefault();
const newImage = document.createElement('img');
const newImageValue =
document.querySelector('#imageLink').value;
if (newImageValue === '') {
alert('Please enter a URL');
return;
}
newImage.src = newImageValue;
newImage.alt = 'Meme Image';
document.body.appendChild(newImage);
document.querySelector("imageLink").reset;
});
您似乎缺少# here document . query selector(& quot;imageLink & quot).選擇導(dǎo)致代碼中斷的代碼時(shí)重置
const form = document.querySelector('#form');
form.addEventListener('submit', function(e) {
e.preventDefault();
const newImage = document.createElement('img');
const newImageValue =
document.querySelector('#imageLink').value;
if (newImageValue === '') {
alert('Please enter a URL');
return;
}
newImage.src = newImageValue;
newImage.alt = 'Meme Image';
document.body.appendChild(newImage);
document.querySelector("#imageLink").reset;
});
<form id="form">
<input id="imageLink">
<button type="submit">Submit</button>
</form>
const form = document.getElementById('form');
const memes = document.getElementById('memes');
form.addEventListener('submit', function (e) {
e.preventDefault();
let f = new FormData(e.target);
let url = f.get("url");
const newImage = document.createElement('img');
if (url === '') {
alert('Please enter a URL');
return;
}
newImage.src = url;
newImage.alt = 'Meme Image';
memes.appendChild(newImage);
e.target.reset();
});
section{
padding:1rem;
}
<form id="form">
<label for="url">Enter an https:// URL:</label>
<input type="url" name="url" id="url"
placeholder="https://example.com"
pattern="https://.*" size="30"
required>
<button>Add</button>
</form>
<section id="memes">
</section>