jQuery获取点击对象的父级
一、使用$('body').on('click','.index',function(event){})绑定事件时,例:
<div class="project-box"> <a href="javascript:void(0)"> <div class="clearfix"> <p>项目名称:</p> <p class="p-name">超级玛丽 for andriod</p> </div> <div class="clearfix"> <p>项目类型:</p> <p class="p-type">游戏开发</p> </div> <div class="clearfix"> <p>项目人员:</p> <p class="p-people">andriod开发工程师 UI设计师</p> </div> <div class="clearfix"> <p class="pro-time">2017-6-15</p> </div> <div class="join-pro"> <button class="join" type="text">点击参与</button> </div> </a> </div>
点击class = "join"获取class="project-box"下的class="p-name":
$('body').on('click','.index',function(event){ var target = event.target; if(target.className === 'join'){ let projectName = $(target).parents(".project-box").find(".p-name").html(); console.log(projectName); } });
二、常规方法获取点击对象的父元素
<div class="col-xs-12 col-sm-6 col-md-3 project-box"> <a href="javascript:void(0)"> <div class="clearfix"> <p>项目名称:</p> <p class="p-name">超级玛丽 for andriod</p> </div> <div class="clearfix"> <p>项目类型:</p> <p class="p-type">游戏开发</p> </div> <div class="clearfix"> <p>项目人员:</p> <p class="p-people">andriod开发工程师 UI设计师</p> </div> <div class="clearfix"> <p class="pro-time">2017-6-15</p> </div> <div class="join-pro"> <button class="join" type="text">点击参与</button> </div> </a> </div>
点击class = "join"获取class="project-box"下的class="p-name":
$(".join).onclick = function(){ $(this).parent().parent().parent().toggle(); }