简体   繁体   English

使用jQuery无法找到被单击元素的父元素的ID

[英]Can't find the id of parent element of clicked element using jquery

I want to get the id of the parent of element of the event on which the mousedown event was performed. 我想获取在其上执行mousedown事件的事件的元素的父代的id I am using the following code: 我正在使用以下代码:

$(document).on("mousedown",function(e) {  
    var id1 = $(e.target).closest("div").attr('id');
    console.log(id1);
});

The output of this is always undefinded . 其输出始终是undefinded I tried this also: 我也尝试过这个:

$(document).on("mousedown",function(e) {  
    var id1 = $(e.target).closest("div");
    console.log(id1);
});

This is the output 这是输出

[div.addmap, prevObject: x.fn.x.init[1], context: div.addmap]

What can I do to get the id attribute of the parent element? 如何获得父元素的id属性? addmap is the id of the parent div . addmap是父divid

The reason you cannot find a parent is, that you have bound the event-listener to the document itself. 找不到父级的原因是,您已将事件侦听器绑定到文档本身。 If you supply a second argument in the form of 如果您以以下形式提供第二个参数

$(document).on('mousedown', 'img', function(e){...})

You will bind the event listener to all <img> elements for example. 例如,您将事件侦听器绑定到所有<img>元素。 Then clicking on an image will produce the desired result. 然后单击图像将产生所需的结果。 Instead if 'img' you could also use 'img,p,span,div' which would bind the listener to all elements being of one if the types specified. 相反,如果使用'img'还可以使用'img,p,span,div' ,它将侦听器绑定到所有指定类型的元素。

If you don't want to be specific you could of course also use '*' binding it to all elements of the document. 如果不想具体说明,当然也可以使用'*'将其绑定到文档的所有元素。

$(document).on("mousedown",function(e) {  
    var id1=$(e.target).parent().attr('id');
    console.log(id1);
});

As I'm assuming binding to the document is intentional in order to register clicks anywhere on the page and get the closest div, the following should do the trick: 我假设绑定到文档是有意的,以便在页面上的任何位置注册点击并获取最接近的div,以下方法可以解决问题:

I've taken onboard Jaromanda X's observation that you seem to be looking for a parent class rather than id ( context: div.addmap ) 我已经在Jaromanda X上进行了观察,发现您似乎在寻找父类而不是id( context: div.addmap

JSFiddle: http://jsfiddle.net/j86rn2mh/1/ JSFiddle: http : //jsfiddle.net/j86rn2mh/1/

jQuery jQuery的

$(document).on("mousedown", function (e) {
var closestDiv = $(e.target).closest('div');
var closestDivClass = closestDiv.parent().attr('class');
console.log(closestDivClass);
});

HTML 的HTML

<div class='addMap'>
<div id='targetDiv'>CLICK ME</div>
</div>

CSS 的CSS

div.addMap {
height: 200px;
width:200px;
border-style: solid;
border-color: black;
}

div#targetDiv {
height: 100px;
width:100px;
border-style: solid;
border-color: yellow;
text-align: center;
}
$(function(){
  $('#elm').click(function(){
    var parentElm = $(this).parent('tagname_or_class_or_id').attr('id');
  });
});

Try this one, It should work :) 试试这个,它应该工作:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM