jquery获得当前元素父级元素,JQuery的:获取点击的元素的父元素的id

I have a div like this:

x

When I click on the 'x' (I want to run a jquery function called disablePopup(id); where id is the id of the coresponding popupDiv (I have many popupDiv each with it's own X button.

in order to do so I implemented the following

$(".popupCloseClass").click(function (event) {

var buttonID = $(event.target).attr("id");

var id = $( buttonID).closest("div").attr("id");

disablePopup(id);

});

basicaly I get the id of the popupCloseClass clicked then I get the id of it's parent (the corresponding popupDiv) via the closest method. then I call disablePopup.

But this is not working.

I even tryed to use the var buttonID = $(buttonID).parent().attr("id"); method but did not work either.

I also tried var id = this.id;

Any help is greatly appreciated

Thanks

解决方案

instead of using closest you can use parent like this...

var id = $(this).parent().attr("id");

Notice you can use the this keyword to reference the element that kicked off the event. As you have it, you are using the value of buttonID as the element selector which would have a value of "popupDivClose" and without adding a # at the start it will not search for an ID, but rather a tag element called "popupDivClose".

If you wanted to keep using buttonID you could have used this line of code to get it working...

var id = $("#" + buttonID).parent().attr("id");

However, I would have preferred to write the whole event like so...

$(".popupCloseClass").click(function (event) {

event.preventDefault();

var id = $(this).parent().attr("id");

disablePopup(id);

});

notice the use of event.preventDefault(); this will ensure that the browser will not process the natural action for a link click (i.e. page navigation) - though, in Chrome at least, you need to specify a href value for the navigation anyway

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值