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

来源:互联网 发布:男士毛孔粗大 知乎 编辑:程序博客网 时间:2024/05/16 05:56

如下代码可以实现点击页面获得被点击元素的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

阅读全文
0 0