首页 > 解决方案 > 从 DOM 输入元素动态创建现有类的新 JS 对象实例

问题描述

在 Javascript for HTML 中,如何创建一个类的新对象实例,其中类中新对象的对象名称/变量名称来自输入元素的文本值?

在这个例子中......我有一个名为 myClass 的类,我创建了一个名为 Chickens 的 myClass 对象实例,其属性“myProperty”的值为 100。假设我想在浏览器中使用名称输入元素来制作一个新的 myClass 对象实例,例如 Dogs,并使用属性输入元素将其 myProperty 值设置为 49。

这是我的例子:

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <input id="name" placeholder="name">
        <input id="property" placeholder="property">
        <button id="btn"></button>
    </body>
    <script src="rhythm-class.js"></script>
</html>

function myClass() {
        this.myProperty
}

let chickens = new myClass()

chickens.myProperty = '100'

console.log(chickens)

let currObj = null
let currProp = null

document.querySelector('#name').addEventListener('change', (e)=> {
        console.log(e.target.value)
        currObj = e.target.value
        let `${e.target.value}` = new myClass
})
document.querySelector('#property').addEventListener('change', (e)=> {
        console.log(e.target.value)
        currentProp = e.target.value
        let `${currentObj}`.testProperty = e.target.value
})
document.querySelector('#btn').addEventListener('click', ()=> {
        console.log(`${currentObj}`.testProperty)
})

标签: javascripthtmlclassobjectdom-events

解决方案


function myClass(value) {
  this.myProperty = value;
}

let chickens = new myClass("100");

console.log(chickens);

let form = document.querySelector("form");
let inputs = form.elements;

form.addEventListener("submit", (e) => {
  e.preventDefault();
  let nameField = inputs["name"];
  let propField = inputs["property"];

  // you can test here if both of the values are set
  window[nameField.value] = new myClass(propField.value);
  console.log(window[nameField.value].myProperty);

});
<!DOCTYPE html>
<html>

<head>
</head>

<body>
  <form>
    <input id="name" placeholder="name">
    <input id="property" placeholder="property">
    <button id="btn">Submit</button>
  </form>
</body>

</html>

由于 JS 中的每个变量都是全局对象的属性,我们可以在这里使用它。请注意,全局对象是window. 我们将全局对象的属性名称设置为我们的实例名称,然后实例化传递我们输入值的类。

建议您使用本地对象来存储变量名,而不是使用全局对象。


推荐阅读