javascript - 我正在尝试使用模板文字在 html 中显示来自 javascript 的文本,但元素未定义,我该怎么办?

标签 javascript html template-literals

我试图在 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/

相关文章:

javascript - 如何使用 javascript 获取 HTML 元素的非计算 marginLeft 样式值?

javascript - 如何在切换选项卡时更改页面标题并播放通知声音?

javascript - ES6 模板文字比 eval 更安全吗?

javascript - 如何防止模板文字中的条件呈现 false

javascript - Tablesorter 不会在初始页面加载时进行排序

javascript - 在 Scrollview 中查看不显示

javascript - 使用 php 动态更改 html 表格单元格内容

javascript - HTML 重置按钮与使用 jQuery 设置的文本字段值相结合

android - 如何在 chrome 应用程序中使用自动完成功能?

javascript - 将长模板文字行包装为多行而不在字符串中创建新行