想使对象的动态值(从用户输入),但我得到“未定义”。想法是有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();">


我也在寻找一种方法,用户可以添加或删除属性(其中的值也是如此)。

最佳答案

Here是您的示例的摘要。

<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时,这些输入包含数据,因此必须在.value()时使用onclick进行读取。如果尝试在onclick部分之外读取它们,则在页面加载期间输入字段为空时将立即访问它们。

关于javascript - 对象属性中的动态值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8363725/

10-10 13:09