我有一个JavaScript代码,可显示列表中某人的姓名和年龄。但是为了调用正确的事件,我需要将下拉列表值传递给要创建的新变量和对象。
在button1下面的相同代码中,按字符串不能正常工作。但是按钮2。
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
var myF = new Person("John", "Doe", 50, "blue");
var myM = new Person("Sally", "Rally", 48, "green");
function test1() {
var per = document.getElementById("peep").value;
document.getElementById("demo").innerHTML = per.firstName + " is " + per.age + " years old"
}
function test2() {
var met = document.getElementById("peep").value;
var mat = document.getElementById("att").value;
//making objects of dropdown values
if (met == "myF") {
var per = myF
} else if (met == "myM") {
var per = myM
};
document.getElementById("demo").innerHTML = per[mat] + " is " + per.age + " years old"
}
<h2>JavaScript Objects</h2>
<select id="peep" name="people">
<option value="myM">mom</option>
<option value="myF">dad</option>
</select>
<select id="att" name="atributes">
<option value="firstName">first</option>
<option value="lastName">last</option>
</select>
<br>
<input type="button" value="Button 1" onclick="test1()">
<input type="button" value="Button 2" onclick="test2()">
<br/>
<p id="demo"></p>