[英]Dynamic values in object properties
想使對象的動態值(從用戶輸入),但我得到“未定義”。 想法是有3個輸入字段,用戶應在其中輸入值,以填滿警報消息。
<script type="text/javascript">
function Family (fatherName, motherName, sisterName) {
this.fatherName = fatherName;
this.motherName = motherName;
this.sisterName = sisterName;
this.myFamily = function() {
alert("My father's name is " + this.fatherName +", my mother's name is "+ this.motherName +" and my sister's name is " + this.sisterName +".");
}
}
var Me = new Family(
Family["fatherName"] = father,
Family["motherName"] = mother,
Family["sisterName"] = siter);
var father = document.getElementById("fatherId").value;
var mother = document.getElementById("motherId").value;
var sister = document.getElementById("sisterId").value;
</script>
<input type="text" id="fatherId" />
<input type="text" id="motherId" />
<input type="text" id="fatherId" />
<input type="submit" value="Send" onclick="Me.myFamily();">
我也在尋找一種方法,用戶可以添加或刪除屬性(它們中的值也是如此)。
您的代碼有些錯誤。
您在這里使用了變量
Family["fatherName"] = father,
Family["motherName"] = mother,
Family["sisterName"] = siter); // This should be sister by the way
在這里聲明他們之前
var father = document.getElementById("fatherId").value;
var mother = document.getElementById("motherId").value;
var sister = document.getElementById("sisterId").value; // Doesn't exist
嘗試切換語句,以便先聲明變量。
另外,沒有sisterId
,您已經使用了fatherId
兩次。
您還需要在DOM准備就緒之前調用javascript。 如果您使用的是jQuery,則將JS包裝在
$(document).ready(function() { }
或者,如果您想使用普通的JS,請嘗試
window.onload = function() { }
您必須更詳細地說明myFamily
應該做什么,因為您甚至都沒有提到該方法。
這是您的示例的工作片段。
<input type="text" id="fatherId" />
<input type="text" id="motherId" />
<input type="text" id="sisterId" />
<input type="submit" value="Send" id="submit" />
<script>
function Family(fatherName, motherName, sisterName) {
this.fatherName = fatherName;
this.motherName = motherName;
this.sisterName = sisterName;
this.myFamily = function() {
alert("My father's name is " + this.fatherName +
", my mother's name is " + this.motherName +
" and my sister's name is " + this.sisterName + ".");
};
}
document.getElementById("submit").onclick = function() {
var father = document.getElementById("fatherId").value;
var mother = document.getElementById("motherId").value;
var sister = document.getElementById("sisterId").value;
Me = new Family(father, mother, sister);
Me.myFamily();
}
</script>
布蘭登很好地總結了所有錯誤。
* 編輯:(回答您的評論)
您的代碼有兩個與執行相關的問題。
<script>
標記會立即執行,因此,如果您在<input>
部分之前插入腳本,則沒有可供檢索的input
元素。 submit
時,這些輸入包含數據,因此必須在onclick
時使用.value()
進行讀取。 如果嘗試在onclick
部分之外讀取它們,則在頁面加載期間輸入字段為空時將立即訪問它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.