javascript - 从 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)
})
解决方案
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
. 我们将全局对象的属性名称设置为我们的实例名称,然后实例化传递我们输入值的类。
建议您使用本地对象来存储变量名,而不是使用全局对象。
推荐阅读
- asp.net-mvc - 拒绝访问路径“C:\inetpub\wwwroot\App_Data\TEMP\PluginCache”。亚马逊 AWS 豆茎
- jbpm - 多实例子流程 inputDataItem
- ios - 我们的 iOS 应用程序被删除后我能做什么?
- pdf - JsReport Chrome-pdf 配方横向选项
- sql - 在oracle中将父子行转换为JSON
- php - 在 HEADER 中使用用户令牌验证 API
- python - csv.DictReader 分隔符在带有多个引号的 csv 字段中
- python-3.x - 将数据从数据框的顶部移动到底部(df 的列具有不同的长度索引)
- java - 为什么节点被添加到错误的链表中?
- cassandra - 第三个 Cassandra 节点有不同的负载