当我点击<li>
元素(点击)时,我触发了此功能
当我点击相同的<li>
元素(unlick)时,我想触发另一个函数。
<ul id="list">
<li>Option1</li>
<li>Option2</li>
<li>Option3</li>
<li>Option4</li>
<li>Option5</li>
<li>Option6</li>
</ul>
<script>
var elems = document.getElementsByTagName('li');
Array.from(elems).forEach(v => v.addEventListener("click", addToArray));
function addToArray() {
}
</script>
请,我正在寻找可以解决问题的纯JavaScript代码。 谢谢
答案 0 :(得分:0)
<script>
var elems = document.getElementsByTagName('li');
Array.from(elems).forEach(v => {
v.addEventListener("click", addToArray));
function addToArray(event) {
if (event.target.classList.includes('active')) {
event.target.classList.split("active").join("");
// unclick handler here
} else {
event.target.classList.push("active");
// click handler here
}
}
</script>
答案 1 :(得分:0)
您可以切换类值并根据它是否存在来执行某些操作,例如
window.onload = function() {
[].forEach.call(document.querySelectorAll('li'), function(li) {
li.addEventListener('click',handleClick,false);
});
};
function handleClick(){
this.classList.toggle('selected');
if (this.classList.contains('selected')) {
console.log(this.textContent + ' is selected');
} else {
console.log(this.textContent + ' isn\'t selected');
}
}
.selected {
background-color: green;
}
<ol>
<li>First
<li>Second
<li>Third
</ol>
请注意, classList 需要IE 10或更高版本。如果需要支持较旧的浏览器,则可以相当简单地编码相同的功能。以下使用 classList 对象提供相同的功能,并将返回到IE 6。
// Helper object to provide classList functionality
var classList = {
contains: function(el, className) {
var re = new RegExp('(^|\\s)' + className + '(\\s|$)');
return re.test(el.className);
},
add: function (el, className) {
if (!classList.contains(el, className)) {
el.className += ' ' + className;
}
},
remove: function(el, className) {
if (classList.contains(el, className)) {
var re = new RegExp('(^|\\s)' + className + '(\\s|$)');
el.className = el.className.replace(re, ' ');
}
},
toggle: function(el, className) {
if (classList.contains(el, className)) {
classList.remove(el, className);
} else {
classList.add(el, className);
}
}
};
window.onload = function() {
var lis = document.getElementsByTagName('li');
for (var i=0, iLen=lis.length; i<iLen; i++) {
lis[i].addEventListener('click', handleClick, false);
}
};
function handleClick(){
classList.toggle(this, 'selected');
if (classList.contains(this, 'selected')) {
console.log(this.innerHTML + ' is seleced');
} else {
console.log(this.innerHTML + ' is not seleced');
}
}
.selected {
background-color: red;
}
<ol>
<li>First
<li>Second
<li>Third
</ol>
答案 2 :(得分:0)
$('#tetrislauncher').click()