如果你的代码仅使用非Chrome API基本的HTML + JavaScript的(这你是),它在普通浏览器页面的环境不行,那么它是不会在Chrome扩展选项页面或弹出窗口工作。
您的代码,因为它是,不会正常工作,因为你正试图从render_form()
的返回值指定为您的事件侦听器:如果更改实际分配render_form
函数作为
addEventListener('click', render_form());
事件收听者:
addEventListener('click', render_form);
它实际上会添加<input>
元素。这可能不完全是你想要的(即counter
总是0
)。
您的问题意味着您希望默认情况下有一个输入字段在那里。因此,我添加了作为侦听器的render_form()
函数的调用。我也移动counter
是全球性的,因此您的计数工作,因为我相信你的愿望。
var counter = 0;
function render_form() {
let newdiv = document.createElement('div');
newdiv.innerHTML="Entry "+(counter + 1)+" <br><input type='text' name='myInputs[]'/>";
document.getElementById('fields').appendChild(newdiv);
counter++;
}
document.getElementById('createNew').addEventListener('click', render_form);
render_form();
<!DOCTYPE html>
<html>
<head><title>My Test Extension Options</title></head>
<body>
<header>
<h1>My Tabs</h1>
</header>
<form id='fields'>
<button id="createNew" type='button'>Add...</button>
</form>
<div id="status"></div>
<button id="save" type='button'>Save</button>
</body>
<!-- Comment out the external script which is required in a Chrome popup,
but which does not work in a Stack Overflow snippet.
<script src="./js/options.js"></script>
-->
</html>
除了这个片段中,我测试了谷歌浏览器上面的代码作为一个扩展的选项页面。在这种情况下它工作正常。
这里是我用来测试这既是一个谷歌Chrome扩展的manifest.json 文件和Firefox的WebExtension [注:的manifest.json使用相同options.html既是options_ui页面和browser_action popup]:
{
"description": "Demonstrate changing the HTML of options.",
"manifest_version": 2,
"name": "change-option-form-demo",
"version": "0.1",
"applications": {
"gecko": {
//Firefox: must define id to use option_ui:
"id": "[email protected]",
"strict_min_version": "48.0"
}
},
"browser_action": {
"default_icon": {
"48": "myIcon.png"
},
"default_title": "Show panel",
"browser_style": true,
"default_popup": "options.html"
},
"options_ui": {
"page": "options.html",
"chrome_style": true
}
}
'的addEventListener( '点击',render_form())'必须'的addEventListener( '点击',render_form)' – Makyen
还加上'型='button''您添加'