古詩詞大全網 - 個性簽名 - jQuery如何實現點擊頁面獲得當前點擊元素的id或其他信息

jQuery如何實現點擊頁面獲得當前點擊元素的id或其他信息

如下代碼可以實現點擊頁面獲得被點擊元素的id

$(document).click(function(e)?{?//?在頁面任意位置點擊而觸發此事件

$(e.target).attr("id");//?e.target表示被點擊的目標

})

示例代碼如下

創建Html元素

<div?class="box">

<span>點擊頁面後,設置被點擊元素背景色並獲取其id:</span><br>

<div?class="content"?id?=?"test">test

<div?id?=?"test1">test1

<div?id?=?"test2">test2

<div?id?=?"test3">test3</div>

</div>

</div>

</div>

</div>

設置css樣式

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;}

編寫jquery代碼

$(function(){

$(document).click(function?(e)?{

$(e.target).addClass('bg');?//?設置背景色

alert($(e.target).attr('id'));?//?獲取id

})

})

觀察效果

初始狀態

點擊id為test2的div