如何检测JavaScript中是否有某些内容被点击? (不使用jQuery)

时间:2014-02-25 15:06:07

标签: javascript javascript-events

我想创建一个布尔函数,可以检测某个元素是否被点击然后输出true或false。我希望在没有jQuery的纯JavaScript中执行此操作,我的想法看起来像这样:

function clicked(whatever-element-I-want) {

  if(whatever-element-I-want==clicked) {
    return true;
  } else {
    return false;
  }
}

我知道这个问题可能看起来很愚蠢,但到目前为止我遇到的所有事情都让我感到困惑,并且真的很喜欢一个简单明了的答案。

3 个答案:

答案 0 :(得分:9)

通常,HTML元素不会跟踪状态,无论是否单击它们。相反,当单击某个元素时,它将触发单击事件。要跟踪元素的点击次数,您可以将状态存储在变量中,并在该元素触发click事件时更新它:

HTML:

<div id="myElement">Click me!</div>

JS:

var elementIsClicked = false; // declare the variable that tracks the state
function clickHandler(){ // declare a function that updates the state
  elementIsClicked = true;
}

var element = document.getElementById('myElement'); // grab a reference to your element
element.addEventListener('click', clickHandler); // associate the function above with the click event

请注意,当您单击该元素时,页面上的所有其他代码都已经执行。通常,基于事件的编程,您希望在事情发生时执行操作。以下是您可以不时检查元素是否已被点击的方法:

// check if the element has been clicked every 2 seconds:
function isElementClicked (){
  console.log(elementIsClicked ? 'CLICKED' : 'NOT');
}
setInterval(isElementClicked, 2000);

答案 1 :(得分:0)

target.addEventListener(type, listener[, useCapture]);

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener

这里的文档就是你的例子:

HTML:

<table id="outside">
    <tr><td id="t1">one</td></tr>
    <tr><td id="t2">two</td></tr>
</table>

的javascript:

// some user defined function
// to change the content of t2
function modifyText(new_text) {
  var t2 = document.getElementById("t2");
  t2.firstChild.nodeValue = new_text;    
}

// get reference to the DOM element with id = "outside" 
// so that we can add whatever listeners: click, change etc.
// Note: not all DOM elements can handle all listeners.    
var el = document.getElementById("outside");

// attach event types to that reference and let it know how
// to handle that event via callback or a function.
// this could be inline function (as in my example below)
// or you could define a function outside and pass its name
// function add(a,b){ return a + b;}
// el.addEventListener("click", add, false);
el.addEventListener("click", function(){
                                modifyText("four")
                             }, false);

答案 2 :(得分:0)

当点击标识为my-button的按钮时,这将提示“点击”:

HTML

<button id="my-button">Click me</button>

的JavaScript

var el = document.getElementById("my-button");

if (el.addEventListener) {
    el.addEventListener("click", function() {
        alert("clicked");
    }, false);
} else { //IE8 support
    el.attachEvent("onclick", function() { 
        alert("clicked");
    });
}

http://jsbin.com/jayutuze/1/edit

现在,根据你提出的问题,如果没有按下按钮,你会想要某种负面反馈,但这有点复杂:是否应该按下一段时间?或者在悬停在它上面时是否应该按下它?请解释一下你想要实现的目标。