有人能帮我一下吗。我正在尝试触发应调用该函数并应显示内容的按钮帖子
不工作(当按钮被合并时)
<button id="alert" type="button">Calling car properties</button>
<script>
document.getElementById("alert").onclick = function car(seats,engine,theradio) {
this.seats=seats;
this.engine=engine;
this.theradio=theradio;
var work_car= new car("cloth","V-7","Tape Deck");
var fun_car= new car("leather","V-8","C Player");
var engine_type= work_car.engine;
var seat_type= fun_car.seats;
var radio_type= fun_car.theradio;
document.write("I want a car with "+seat_type+" seats.<br />");
document.write("It also needs a "+engine_type+" engine.<br />");
document.write(radio_type);
var number = Math.random();
document.write("It also needs a "+number+" engine.<br />");
}
</script>
无按钮工作
<script>
function car(seats,engine,theradio) {
this.seats=seats;
this.engine=engine;
this.theradio=theradio;
}
var work_car= new car("cloth","V-7","Tape Deck");
var fun_car= new car("leather","V-8","C Player");
var engine_type= work_car.engine;
var seat_type= fun_car.seats;
var radio_type= fun_car.theradio;
document.write("I want a car with "+seat_type+" seats.<br />");
document.write("It also needs a "+engine_type+" engine.<br />");
document.write(radio_type);
var number = Math.random();
document.write("It also needs a "+number+" engine.<br />");
</script>
如评论中所述,您car
递归调用函数。要解决此问题,只需重命名onclick
事件名称并保留car
函数即可。
function car(seats, engine, theradio) {
this.seats = seats;
this.engine = engine;
this.theradio = theradio;
}
document.getElementById("alert").onclick = function event() {
var work_car = new car("cloth", "V-7", "Tape Deck");
var fun_car = new car("leather", "V-8", "C Player");
var engine_type = work_car.engine;
var seat_type = fun_car.seats;
var radio_type = fun_car.theradio;
document.write("I want a car with " + seat_type + " seats.<br />");
document.write("It also needs a " + engine_type + " engine.<br />");
document.write(radio_type);
var number = Math.random();
document.write("It also needs a " + number + " engine.<br />");
}
<button id="alert" type="button">Calling car properties</button>
您必须注意的另一件重要事情是document.write
。可能更好的方法是创建标签并将其附加到正文中。像这样:
var div1 = document.createElement("div");
div1.innerHTML = "I want a car with " + seat_type + " seats.<br />";
document.body.append(div1);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句