JQuery: Get the parent element id of a clicked element

后端 未结 4 414
鱼传尺愫
鱼传尺愫 2021-01-18 01:38

I have a div like this:

x
相关标签:
4条回答
  • 2021-01-18 01:40

    This works fine:

    $('a.popupCloseClass').click(function() {
        var id = $(this).parent().attr('id');
    });​
    

    JSFiddle Demo

    You should just use this instead of the way you are getting the ID and then trying to use it as a selector (you were missing the # before the ID):

    0 讨论(0)
  • 2021-01-18 01:48

    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

    Here is a working example

    0 讨论(0)
  • 2021-01-18 01:48

    This must work:

    $(".popupCloseClass").click(function (event) 
    {
        var buttonID = $(this).parent().attr('id');
        disablePopup(buttonID);
    });
    
    0 讨论(0)
  • 2021-01-18 02:05

    You should do

    $(".popupCloseClass").click(function (event) {
        var id = $(this).closest("div").attr("id");
    });
    

    (you could also use $(this).parent().attr("id"); ) but using closest is safer in case you change your html structure

    0 讨论(0)
提交回复
热议问题