[英]Cannot Create Alert Message for User When Radio Button Option is Submitted - Javascript/HTML
我對 Javascript 還很陌生。 我有一個 chrome 擴展,其中有 2 個單選按鈕供用戶選擇(選項稱為 Facebook 或 Instagram)。 當他們選擇一個並按“保存”時,我希望彈出一條警報消息,只是為了讓用戶知道它已保存。 我已經嘗試了很多我在 Stack Overflow 上看到的不同的東西,但它們都沒有奏效,所以我不確定我是否只是不明白把代碼放在哪里?
單擊保存按鈕時,如何創建簡單的警報? 例如,我嘗試使用 onsubmit 事件,但什么也沒發生。 代碼已經完成了它應該做的事情 - Javascript 文件正確地阻止了兩個網站之一,具體取決於單擊的單選按鈕。 這樣代碼就設置好了。 我似乎無法弄清楚如何生成警報。
HTML:
<!DOCTYPE html>
<html>
<head><title>User Options</title></head>
<body>
Which website should I block?<br><br>
<label><input type="radio" name="blockingMethod" id="close_tab"
value="close_tab" checked> Facebook <br></label>
<label><input type="radio" name="blockingMethod" id="closetab"
value="closetab" checked> Instagram <br></label>
<br><br>
<input type="submit" id="save" value="save">
<script src="background.js"></script>
</body>
JAVASCRIPT 文件:
let closingMethodRadios = document.getElementsByName('blockingMethod');
let saveButton = document.getElementById('save');
document.addEventListener('DOMContentLoaded', function() {
if(saveButton) {
saveButton.addEventListener('click', function() {
if(closingMethodRadios[0].checked){
chrome.storage.sync.set({'blockingMethod': 'close_tab'}),
chrome.webRequest.onBeforeRequest.addListener(
() => ({cancel: true}),
{
urls: ['*://*.facebook.com/*'],
types: ['main_frame'],
},
['blocking']);
}
if (closingMethodRadios[1].checked) {
chrome.storage.sync.set({'blockingMethod': "closetab"}),
chrome.webRequest.onBeforeRequest.addListener(
() => ({cancel: true}),
{
urls: ['*://*.instagram.com/*'],
types: ['main_frame'],
},
['blocking']);
}
});
}
});
你只需要在 javascript 中使用警報功能,你已經有了 onclick 方法,只需在那里添加一個警報,如下所示:
let closingMethodRadios = document.getElementsByName('blockingMethod'); let saveButton = document.getElementById('save'); document.addEventListener('DOMContentLoaded', function() { if(saveButton) { saveButton.addEventListener('click', function() { alert("Option Saved") if(closingMethodRadios[0].checked){ chrome.storage.sync.set({'blockingMethod': 'close_tab'}), chrome.webRequest.onBeforeRequest.addListener( () => ({cancel: true}), { urls: ['*://*.facebook.com/*'], types: ['main_frame'], }, ['blocking']); } if (closingMethodRadios[1].checked) { chrome.storage.sync.set({'blockingMethod': "closetab"}), chrome.webRequest.onBeforeRequest.addListener( () => ({cancel: true}), { urls: ['*://*.instagram.com/*'], types: ['main_frame'], }, ['blocking']); } }); } });
<!DOCTYPE html> <html> <head><title>User Options</title></head> <body> Which website should I block?<br><br> <label><input type="radio" name="blockingMethod" id="close_tab" value="close_tab" checked> Facebook <br></label> <label><input type="radio" name="blockingMethod" id="closetab" value="closetab" checked> Instagram <br></label> <br><br> <input type="submit" id="save" value="save"> <script src="background.js"></script> </body>
jsFiddle: https ://jsfiddle.net/ryzuc1n7/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.