Javascript 按钮启用或禁用

时间:2021-01-19 18:05:18

标签: javascript button

我希望第一个函数 haritaOne 在我按下按钮时起作用,当我再次按下它时,我如何运行第二个函数 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>

3 个答案:

答案 0 :(得分:0)

使用一个跟踪状态的变量使其成为一个函数

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>

现在我认为您正在尝试切换叠加层,这意味着您需要实际删除它,而不仅仅是调用一些随机函数

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);
}

答案 1 :(得分:0)

您可以尝试在 JS 中使用三元运算符。

const counter = 0
counter>1 ? haritaTwo() : haritaOne()

并在 haritaOne() 中为计数器添加一个增量行

function haritaOne() {
        var harita = document.getElementById('map-canvas');
        harita.style.left = "0px";
        counter = counter + 1
    }

它只是一个逻辑解释,您可以对语法进行必要的更改

答案 2 :(得分:0)

如果您希望同时保留这两个功能,您可以使用 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);
相关问题