<button onclick = "button javascript.js">
What do you drive? </button>
我希望按钮在按钮javascript.js文件中运行我的开关()
var car = prompt('What car?');
switch(car) {
case 'ferrari':
document.write("you are probs a baller then");
break;
case "porsche":
document.write("do you ball hard?");
break;
case "dodge":
document.write("american cannot corner");
break;
default:
document.write("your car better be a subaru");
}
答案 0 :(得分:1)
您可以将代码放在javascript中的函数中。将文件包含在脚本标记中,单击该按钮,调用该函数。这将仅在单击按钮时触发JS代码。
将它放在HTML中,
<script src='button javascript.js'></script>
//Intermediate HTML code
<button onclick = "myButtonFun()">
What do you drive? </button>
在Javascript中,您可以在函数myButtonFun()
function myButtonFun()
{
var car = prompt('What car?');
switch(car) {
case 'ferrari': document.write("you are probs a baller then");
break;
case "porsche": document.write("do you ball hard?");
break;
case "dodge": document.write("american cannot corner");
break;
default: document.write("your car better be a subaru");
}
}
答案 1 :(得分:0)
将代码转换为函数,然后在按钮上使用
type="button"
和
onclick="yourFunction()"
答案 2 :(得分:0)
您需要将脚本包装成函数并在按钮单击时调用它:
<button onclick = "askForCar();">What do you drive?</button>
var askForCar = function() {
//you script here
};
var askCar = function() {
switch (prompt('What car?')) {
case 'ferrari':
document.write("you are probs a baller then");
break;
case "porsche":
document.write("do you ball hard?");
break;
case "dodge":
document.write("american cannot corner");
break;
default:
document.write("your car better be a subaru");
}
};
&#13;
<button onclick="askCar();">What do you drive?</button>
&#13;