[英]Javascript Button Enable or Disable
我想要第一個 function haritaOne
在我按下按鈕時工作,當我再次按下它時,如何運行第二個 function, haritaTwo
?
function haritaOne() { var harita = document.getElementById('map-canvas'); harita.style.left = "0px"; } function haritaTwo() { var harita = document.getElementById('map-canvas'); const trafficLayer = new google.maps.TrafficLayer(); trafficLayer.setMap(map); harita.style.left = "0px"; }
<a href="#" onclick="javascript: haritaOne();"</a>
使其成為一個 function 並帶有一個跟蹤 state 的變量
var yourState = false
function yourFunction() {
var harita = document.getElementById('map-canvas');
harita.style.left = "0px";
if (yourState) {
const trafficLayer = new google.maps.TrafficLayer();
trafficLayer.setMap(map);
}
yourState = !yourState;
}
var yourState = false function yourFunction() { console.log('yourFunction called'); if (yourState) { console.log('In True'); } else { console.log('In False'); } yourState =;yourState; }
<button type="button" onclick="yourFunction()">Click</button>
現在我認為您正在嘗試切換覆蓋,這意味着您需要實際刪除它,而不僅僅是調用一些隨機 function
var trafficState = null;
var trafficOverlay = null;
function haritaOne() {
// create overlay if it has yet to be created
if (!trafficOverlay) {
trafficOverlay = new google.maps.TrafficLayer();
}
// get the new state of the overlay
trafficState = trafficState ? null : map;
//set the overlay
trafficOverlay.setMap(trafficState);
}
您可以嘗試在 JS 中使用三元運算符。
const counter = 0
counter>1 ? haritaTwo() : haritaOne()
並在 haritaOne() 中為計數器添加一條增量線
function haritaOne() {
var harita = document.getElementById('map-canvas');
harita.style.left = "0px";
counter = counter + 1
}
它只是一個邏輯解釋,您可以對語法進行必要的更改
如果您希望同時保留 function,您可以使用 Javascript 編輯按鈕:
function haritaOne(event) {
var harita = document.getElementById('map-canvas');
harita.style.left = "0px";
event.target.onclick = haritaTwo;
}
function haritaTwo() {
var harita = document.getElementById('map-canvas');
const trafficLayer = new google.maps.TrafficLayer();
trafficLayer.setMap(map);
harita.style.left = "0px";
}
<a href="#" onclick="javascript: haritaOne(event);"></a>
您可以替換event.target.onclick = haritaTwo;
和:
event.target.removeEventListener(haritaOne);
event.target.addEventListener(haritaTwo);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.