使用jQuery确定单击了哪个元素id或类

Identify which element id or class was clicked using jQuery?

本文关键字:元素 id 或类 jQuery 单击 使用      更新时间:2023-09-26

假设我有

<body>
 <div id="stuff">
  <div id="cat">a</div>
  <div id="dog">b</div>
  <div id="elephant">c</div>
  <div id="rabbit">d</div>
  <div id="frog">e</div>  
 </div>
</body>​

到目前为止,我能得到的壁橱是与JS,

document.getElement('body').onclick = function(e){
    alert(e.target.innerHTML);
}​

当我想要像"猫"或"狗"这样的文字div id而不是"a"或"b"时,它打印出div的内容。我也在尝试使用jQuery来完成这个,我在正确的方向吗?

为了使用jQuery方法,你需要包含jQuery js文件。

与jQuery

$('body').click(function(e){
    alert(e.target.innerHTML);
    alert(e.target.id)
    alert($(e.target).attr('id'));
}​);
使用Javascript

document.getElement('body').onclick = function(e){
    alert(e.target.innerHTML);
    alert(e.target.id)
}​

使用JQuery的html页面示例

<!DOCTYPE html>
 <html lang="en">
 <head>
   <meta charset="utf-8">
   <title>jQuery demo</title>
 </head>
 <body>
   <a href="http://jquery.com/">jQuery</a>
   <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
   <script type="text/javascript">
     document.getElement('body').onclick = function(e){
        alert(e.target.innerHTML);
        alert(e.target.id)
     }​
   </script>
 </body>
</html>

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

document.getElementById('stuff').onclick = function( e ){
    alert( e.target.id );
};

金桥道:

$('#stuff').click(function( e ){
    alert( e.target.id );
});

如果它没有ID,但是有CLASS(并且你想要它!),你可以这样做:

http://jsbin.com/ohotuv/3/edit -(其中"elephant"是一个类)

$('#stuff').click(function( e ){
    var name = e.target.id || e.target.className;
    alert(name);
});

如果您使用纯javascript,您可能需要使其跨浏览器兼容。

window.onload=function(){
    document.getElementsByTagName('body')[0].onclick = function(e){
        e = e ? e : window.event;
        var source = e.target || e.srcElement;
        alert(source.id);
    }
}

我建议阅读一下jQuery.on()

在你的例子中,我建议:

$("body").on("click", function(event){
  alert($(this).id);
});

尽管强烈建议减少作用域,但您要查找的是单击事件中的哪些元素。例如:

$("#stuff").on("click", "div", function(event){
  alert($(this).id);
});

这将只处理任何div元素内的html标签的东西的id。减少处理事件的上下文有助于封装和调试问题。