簡體   English   中英

從 DOM 輸入元素動態創建現有 class 的新 JS object 實例

[英]Create a new JS object instance of an existing class dynamically from a DOM input element

In Javascript for HTML how can I create a new object instance of a class where the object name / variable name of a new object in the class comes from the text value of an input element?

在這個例子中......我有一個名為 myClass 的 class 並且我創建了一個名為 Chickens 的 myClass object 實例,其屬性“myProperty”的值為 100。假設我想在瀏覽器中使用名稱輸入元素來制作一個新的 myClass object 實例,例如 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 中的每個變量都是全局 object 的屬性,我們可以在這里使用它。 請注意,全局 object 是window 我們將全局 object 的屬性名稱設置為我們的實例名稱,然后通過我們的輸入值實例化 class。

建議您使用本地 object 來存儲變量名,而不是使用全局 object。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM