jQuery如何实现点击页面获得当前点击元素的id或其他信息

如下代码可以实现点击页面获得被点击元素的id

1
2
3
$(document).click( function (e) {  // 在页面任意位置点击而触发此事件
   $(e.target).attr( "id" );        // e.target表示被点击的目标
})

示例代码如下

  1. 创建Html元素

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    < div  class = "box" >
         < span >点击页面后,设置被点击元素背景色并获取其id:</ span >
         < div  class = "content"  id = "test">test
             < div  id = "test1">test1
                 < div  id = "test2">test2
                     < div  id = "test3">test3</ div >
                 </ div >
             </ div >
         </ div >
    </ div >
  2. 设置css样式

    1
    2
    3
    4
    5
    div.box{ width : 300px ; padding : 20px ; margin : 20px ; border : 4px  dashed  #ccc ;}
    div.box span{ color : #999 ; font-style : italic ;}
    div.content{ width : 250px ; margin : 10px  0 ; padding : 20px ; border : 2px  solid  #ff6666 ;}
    div.content div{ min-width : 20px ; min-height : 20px ; padding : 30px ; border : 1px  solid  #446699 ; background : #ffffff ;}
    .bg{ background : #ff99cc  !important ;}
  3. 编写jquery代码

    1
    2
    3
    4
    5
    6
    $( function (){
         $(document).click( function  (e) {
             $(e.target).addClass( 'bg' );      // 设置背景色
             alert($(e.target).attr( 'id' ));   // 获取id
         })
    })
  4. 观察效果

  • 初始状态

  • 点击id为test2的div

猜你喜欢

转载自blog.csdn.net/qq_34752829/article/details/77989812
今日推荐