JQuery的:获取点击的元素的父元素的id [英] JQuery: Get the parent element id of a clicked element

查看:799
本文介绍了JQuery的:获取点击的元素的父元素的id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样一个div:

<div id="popupDiv1" class="popupDivClass">
    <a id="popupDivClose" class="popupCloseClass">x</a>
</div>

当我点击X(我要运行 disablePopup(ID)称为一个jQuery功能; 其中id是coresponding popupDiv的ID(我有许多popupDiv每个都有它自己的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我得到popupCloseClass的id点击然后我得到的id是通过最接近的方法父(对应popupDiv)。然后,我打电话disablePopup。

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.

但是,这是行不通的。

我甚至tryed使用 VAR buttonID = $(buttonID).parent()ATTR(ID); 方法,但也不能工作。

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

我也试过 VAR ID = this.id;

任何帮助是极大AP preciated

Any help is greatly appreciated

感谢

推荐答案

而不是使用最接近您可以使用像这样...

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

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

注意,你可以使用这个关键字来引用拉开序幕事件的元素。当你拥有它,你正在使用的元素选择 buttonID 的值,这将对popupDivClose和没有它不会搜索一个ID开始添加,而是被称为popupDivClose标签元素

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".

如果你想使用buttonID你也可以使用这条线code,以获得它的工作,保持...

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");

不过,我会pferred写出像这样整个事件$ P $ ...

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

注意使用事件preventDefault()的; 这将确保浏览器将无法处理链接点击(即页面导航)的自然动作 - 虽然,在Chrome中至少需要无论如何指定导航href的值

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

这里是

这篇关于JQuery的:获取点击的元素的父元素的id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆