您好,我刚刚学习了javascript查询事件处理函数,由于某种原因,即使我刚在结束body标签之前就导入了javascript,javascript也会在加载时执行
也由于某种原因,onclick事件未触发,请有人告诉我原因!谢谢!
var starter=0;
var type;
var addstarter=document.querySelector("#addstarter");
addstarter.addEventListener("click",calculate("addstarter"));
var minusstarter=document.querySelector("#minusstarter");
minusstarter.addEventListener("click",calculate("minusstarter"));
function calculate(type)
{
switch(type)
{
case'addstarter': starter=starter+1;
break;
case 'minusstarter':starter=starter-1;
break;
}
alert(starter);
}
#Starter
{
float:left;
width:25%;
height:40%;
background-color:rgb(55, 128, 85);
color: white;
margin: 5% 1% 1% 4%;
padding: 1% 1% 1% 1%;
color: black;
border-radius: 10% 10% 10% 10%;
}
#Starter img
{
width:50%;
margin-top: -5%;
}
<main>
<div id="Starter">
<div class="card_border">
<div class="card_heading">
<p> Starter Pack </p>
</div>
<div class="card_content">
<input type="button" value="+" class=" button button1" id="addstarter"/>
<a href="https://en.wikipedia.org/wiki/Entr%C3%A9e"><img src="images/starterr.png"></a>
<input type="button" value="-" class=" button button2" id="minusstarter"/>
<span class="tooltiptext">$5</span>
</div>
</div>
</div>
答案 0 :(得分:1)
您需要替换:
addstarter.addEventListener("click", calculate("addstarter"));
收件人:
addstarter.addEventListener("click", () => calculate("addstarter"));
var starter=0;
var type;
var addstarter=document.querySelector("#addstarter");
addstarter.addEventListener("click", () => calculate("addstarter"));
var minusstarter=document.querySelector("#minusstarter");
minusstarter.addEventListener("click", () => calculate("minusstarter"));
function calculate(type)
{
switch(type)
{
case'addstarter': starter=starter+1;
break;
case 'minusstarter':starter=starter-1;
break;
}
alert(starter);
}
#Starter
{
float:left;
width:25%;
height:40%;
background-color:rgb(55, 128, 85);
color: white;
margin: 5% 1% 1% 4%;
padding: 1% 1% 1% 1%;
color: black;
border-radius: 10% 10% 10% 10%;
}
#Starter img
{
width:50%;
margin-top: -5%;
}
<main>
<div id="Starter">
<div class="card_border">
<div class="card_heading">
<p> Starter Pack </p>
</div>
<div class="card_content">
<input type="button" value="+" class=" button button1" id="addstarter"/>
<a href="https://en.wikipedia.org/wiki/Entr%C3%A9e"><img src="images/starterr.png"></a>
<input type="button" value="-" class=" button button2" id="minusstarter"/>
<span class="tooltiptext">$5</span>
</div>
</div>
</div>