我在创建的网页上遇到一个元素问题,该元素应该在单击时运行,但仅在单击一次后运行。所以第一次点击什么都不做,而所有其他点击都按预期工作。这是我的代码:
HTML:
<div>
<a href="#0" class="packservice" id="rent">Rentals</a>
</div>
<div id="myDIV">
<div class="divinfo">
<div class="servicestxt">
<h2> Rentals </h2>
<hr>
<br>
<p>Rent professional beverage serving equpment for your next event. This is our self serve option.</p><br>
<a href="#0" id="renBut"> Add to Quote </a>
</div>
</div>
</div>
CSS:
#myDIV {
display: none;
color: black;
padding: 2.5% 71.5% 1.5% 1%;
background-color: white;
}
a.packservice {
padding: 1% 97% 1% 1%;
background: gray;
opacity: 0.5;
font-family: 'Oswald', sans-serif;
font-weight: 900;
color: white;
margin-top: .25%;
display: block;
}
#packhead {
font-family: 'Oswald', sans-serif;
}
.divinfo {
width: 250%;
display: block;
background-color: white;
margin-left: 50%;
overflow: auto;
}
JavaScript:
var renBut = document.getElementById("renBut");
var rent = document.getElementById("rent");
function rentalStore() {
if (renBut.innerHTML=="Add to Quote"){
sessionStorage.setItem("rental", true);
renBut.innerHTML = "Remove from Quote"
} else {
sessionStorage.removeItem("rental");
renBut.innerHTML = "Add to Quote";
}
}
//Create function to hide rentals information div
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
function clickDom() {
// Create event to listen for click and call corresponding function
console.log("Entering clickDom() function");
if (rent.addEventListener) {
rent.addEventListener("click", myFunction, false);
}
}
function buttonEl() {
if (renBut.addEventListener) {
renBut.addEventListener("click", rentalStore, false);
}
}
if (window.addEventListener) {
//call init() on page load
console.log("> Adding TC39 Event Listener...");
window.addEventListener ("load", buttonEl, false);
}
if (window.addEventListener) {
console.log("> Adding TC39 Event Listener...");
window.addEventListener ("load", clickDom, false);
}
我也将它上传到代码笔:https://codepen.io/seanbarker182/pen/maexPd
javascript 在这里做了两件事,第一件事就是在点击时简单地取消隐藏或隐藏 div,因此它要求用户首先点击“出租”,它显示我遇到问题的区域是 '添加到报价'按钮。您会注意到第一次点击什么也没做,而第二次或任何后续点击都按预期进行。
有谁知道为什么需要第一次点击才能工作?
最佳答案
问题很简单,感谢添加codepen!
在您的 HTML 中,您有以下内容:
<a href="#0" id="renBut"> Add to Quote </a>
但是,在你的 JS 中你有:
if (renBut.innerHTML=="Add to Quote"){
在运行时 renBut.innerHTML
将评估为 "Add to Quote "
,请注意两端的额外空格。可以通过两种方式应用修复:
删除 HTML 空格
<a href="#0" id="renBut">Add to Quote</a>
使 JavaScript 空白独立
if (renBut.innerHTML.trim()=="Add to Quote"){
您采用哪种方式只是个人喜好,但我个人会选择这两种方式以确保一致性和 future 验证。
关于javascript - 元素需要点击两次才能运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53765671/