Javascript 是否可以在 DIV 上添加事件侦听器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4164053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to add an eventlistener on a DIV?
提问by Roskvist
I know this function:
我知道这个功能:
document.addEventListener('touchstart', function(event) {
alert(event.touches.length);
}, false);
But is it possible to add this to a div? Example:
但是可以将它添加到 div 中吗?例子:
document.getElementById("div").addEventListener('touchstart', function(event) {
alert(event.touches.length);
}, false);
I haven't tested it yet, maybe some of you know if it works?
我还没有测试过,也许你们中的一些人知道它是否有效?
回答by iRyanBell
Yeah, that's how you do it.
是的,你就是这样做的。
document.getElementById("div").addEventListener("touchstart", touchHandler, false);
document.getElementById("div").addEventListener("touchmove", touchHandler, false);
document.getElementById("div").addEventListener("touchend", touchHandler, false);
function touchHandler(e) {
if (e.type == "touchstart") {
alert("You touched the screen!");
} else if (e.type == "touchmove") {
alert("You moved your finger!");
} else if (e.type == "touchend" || e.type == "touchcancel") {
alert("You removed your finger from the screen!");
}
}
Or with jQuery
或者使用 jQuery
$(function(){
$("#div").bind("touchstart", function (event) {
alert(event.touches.length);
});
});
回答by Kiran Solkar
The other way round if you are not using addEventListener, probably a alternative to get control over ID.
相反,如果您不使用 addEventListener,则可能是控制 ID 的替代方法。
$(document).ready(function () {
$('#container1').on("contextmenu", function (e) {
e.preventDefault();
});
});
回答by rawatDigamber
Of course, let's assume you have to insert text in h1element when a user clicks on the button. It's pretty easy to bind HTML's specific element to addEventListener()method
当然,假设您必须在用户单击按钮时在h1元素中插入文本。将 HTML 的特定元素绑定到addEventListener()方法非常容易
<button id="button">Show me</button>
<h1 id="name"></h1>
document.getElementById("button").addEventListener("click", function(){
document.getElementById("name").innerHTML = "Hello World!";
});