js(jQuery)获取当前对象的id,并对其增加样式
这其实是一个比较简单的js,但由于本人并不擅长js,顶多也就会点皮毛,简简单单的能看懂或写出简简单单的js而已...
由于项目开发的过程中,一个功能需要点击时获取当前点击对象的id,很明显,这是一个事件。之前一直都习惯性用写原生js,现在想试试jQuery,毕竟jQuery比较流行,咱们做技术的也不能不思进步是不o(∩_∩)o
本来对jQuery就不感冒,度娘的时候也没有几个正确的答案,捣腾了一上午,终于把这个功能实现了。
下面直接上代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="http://www.chingli.net/wp-content/uploads/2016/04/jquery-2.0.0.min.js" type=text/javascript></script> <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;} </style> <script> $(function(){ $('.content').click(function (e) { $(e.target).addClass('bg'); // 设置背景色 alert($(e.target).attr('id')); // 获取id }) }) </script> </head> <body> <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> </body> </html>
下面看效果展示图:
仅有 1 条评论