我正在使用Javascript HTML DOM事件,当我在浏览器中运行代码时,它说statusHtmlFromObject未定义。有人可以告诉我在html标签中写它的正确方法是什么,就像我想做的那样。我已经附加了script.js文件。
File: Script.js
function statusHtmlFromObject() {
var x = document.getElementById("mySelect").value;
console.log('This is your selection', x);
}
var html = '';
html +='<select id="mySelect" onchange="statusHtmlFromObject()">';
html +='<option value="Order placed">Order placed';
html +='<option value="Preparing">Preparing...';
html +='<option value="Packaging">Packaging...';
html +='<option value="Food is ready">Food is ready';
html +='</select>';
return html;
答案 0 :(得分:0)
const container = document.getElementById('container');
function statusHtmlFromObject() {
var x = document.getElementById("mySelect").value;
console.log('This is your selection', x);
}
var html = '';
html +='<select id="mySelect" onchange="statusHtmlFromObject()">';
html +='<option value="Order placed">Order placed';
html +='<option value="Preparing">Preparing...';
html +='<option value="Packaging">Packaging...';
html +='<option value="Food is ready">Food is ready';
html +='</select>';
container.innerHTML += html;
<div id="container"></div>
<script src=""><script/>
这正在工作。通常,您应该将html附加到div标签或任何其他html元素上。
答案 1 :(得分:0)
您的statusHtmlFromObject函数在另一个函数中声明。 对于onchange事件,它必须是全局可访问的。 这是错误的原因。
您需要在外部声明它或只是在全局范围内定义它:
var statusHtmlFromObject = function (){
...
};