The following code can be used to click on the page to obtain the id of the clicked element$(document).click(function(e)?{?//?Click anywhere on the page to trigger this event$(e.target ).attr("id");//?e.target indicates the clicked target
})
The sample code is as follows
Create Html element< div?class="box">
After clicking on the page, set the background color of the clicked element and obtain its id:
Set css style 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;}
Write jquery code $(function(){
< p> $(document).click(function?(e)?{$(e.target).addClass('bg');?//?Set the background color
alert($(e.target).attr('id'));?//?Get id
})
})
Observe Effect
Initial state
Click on the div with the ID test2