我试图在 html 中的outerText div 中显示名称和选定的形状元素,但它们一直显示为未定义。
here is the Javascript
let ShapeLink = (function(){
//code here!
return {
initForm: function(frm){
//code here!
frm.addEventListener('submit', function(){
document.getElementById('name').name,
document.getElementById('shapeSelect').option;
})
let display = document.getElementById('outputText').innerHTML =
`${this.name} wants to see a ${this.shapeSelect}`;
console.log(display);
display.innerHTML =`
<div id="outputText">
${this.name} wants to see a ${this.shapeSelect}
</div>`
}
}
})()
这是 html
<body>
<form>
<label for="name">Name:</label>
<input type="text" id="name">
<label for="shapeSelect">Shape:</label>
<select name="" id="shapeSelect">
<option value="">pick a shape</option>
<option value="square">Square</option>
<option value="circle">Circle</option>
</select>
<input type="submit" value="Submit">
</form>
<div id="outputText"></div>
<svg width=100 height=100></svg>
<script>
ShapeLink.initForm(document.querySelector("form"));
</script>
</body>
请注意,我需要将所有代码添加到 Javascript 文件中
最佳答案
您应该将所有 JavaScript 放在一起,并且无需将 main 函数设置为全局。除此之外,依赖this
可能会让你陷入受伤的世界。由于您已经可以通过 frm
访问表单,因此您也可以访问其 elements
属性来从表单中获取值:
document.addEventListener('DOMContentLoaded', function() {
const ShapeLink = {
initForm: function(frm) {
frm.addEventListener('submit', function(event) {
event.preventDefault();
event.stopPropagation();
let display = document.getElementById('outputText');
display.innerHTML = `
<div id="outputText">
${frm.elements.name.value} wants to see a ${frm.elements.shapeSelect.value}
</div>
`;
});
},
};
ShapeLink.initForm(document.querySelector('form'));
});
<form>
<label for="name">Name:</label>
<input type="text" id="name">
<label for="shapeSelect">Shape:</label>
<select name="" id="shapeSelect">
<option value="">pick a shape</option>
<option value="square">Square</option>
<option value="circle">Circle</option>
</select>
<input type="submit" value="Submit">
</form>
<div id="outputText"></div>
<svg width=100 height=100></svg>
关于javascript - 我正在尝试使用模板文字在 html 中显示来自 javascript 的文本,但元素未定义,我该怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50048914/