使用js函数消除事件的备用麻烦

时间:2019-04-04 23:11:57

标签: javascript dom-events

有一个简单的(我认为是)函数来添加和删除事件。 在添加中效果很好,但从移除中效果不佳。

我在其他尝试的代码中进行了评论。

  var wrnOn = function() { document.getElementById("accuort").style.display = "block"; }
var wrnOff = function() { document.getElementById("accuort").style.display = "none"; }

function toggleIcon( /*id, imgUrlOn, imgUrlOff*/ ) {

  if (emptyFormChecking()) {
    document.getElementById('advan').src = "img/filter.png";
    document.getElementById("accuort").style.display = "none";
    document.getElementById('submits').removeEventListener("mouseover", wrnOn, true);
    document.getElementById('submits').removeEventListener("mouseout", wrnOff, true);
  } else {
    document.getElementById('advan').src = "img/activefilter.png";
    let x = getOffset(document.getElementById('submits')).left;
    let y = getOffset(document.getElementById('submits')).top;
    document.getElementById('accuort').style.left = (x + 61) + "px";
    document.getElementById('accuort').style.top = (y + 32) + "px";
    document.getElementById('submits').addEventListener("mouseover", wrnOn, true);
    document.getElementById('submits').addEventListener("mouseout", wrnOff, true);
  }
}

怎么了?

1 个答案:

答案 0 :(得分:0)

已解决
(哦,该死!我很...愧...太简单了!)

function toggleIcon() {
	if (emptyFormChecking()) {
		document.getElementById('advan').src = "img/filter.png";
		onOff(false);
	}
	else {	
		document.getElementById('advan').src = "img/activefilter.png";
		let x = getOffset(document.getElementById('submits')).left;
		let y = getOffset(document.getElementById('submits')).top;
		document.getElementById('accuort').style.left = (x+61)+"px";
		document.getElementById('accuort').style.top = (y+32)+"px";
		onOff(true);
	}
}

和上游

var wrnOn = function() { document.getElementById("accuort").style.display = "block"; }
var wrnOff = function() { document.getElementById("accuort").style.display = "none"; }
function onOff(flag) {
	if (flag) {
		document.getElementById('submits').addEventListener("mouseover", wrnOn, true);
		document.getElementById('submits').addEventListener("mouseout", wrnOff, true);
	}
	else {
		document.getElementById("accuort").style.display = "none";
		document.getElementById('submits').removeEventListener("mouseover", wrnOn, true);
		document.getElementById('submits').removeEventListener("mouseout", wrnOff, true);
	}
}

谢谢大家!