简体   繁体   中英

How to get the id of surrounding a element?

I have the following code an I'm trying to determine the id of the a-element:

<li>
 <a class="selectTour" id="32">
   <span>Bla</span>

   <div class="margin-top-2"><font style="white-space:normal; font-size: small">Test 22</font></div>

   <p class="ui-li-aside"><strong>Created</strong>
 </a>
</li>

I cannot use an href element for routing because of the used data framework (backbone.js). I've tried to bind a function on the selectTour class an then I tried to get the id via an event listener (btw the selecTour appears n-times):

selectTour:function(event) {
            $.mobile.loading("show");
            var tour_id = event.target.id;

            this.router.navigate("tour/" + tour_id, {trigger: true})
        },

The problem is that when the user clicks (for example) on the font element (or an other element than the a element) the wrong id is returned. It seems to me this is a standard javascript/jquery question but I can't figure it out and need a push into the right direction.

You can use .closest() to find the closest selectTour element of the click's target then use .attr() to get its id.

selectTour: function (event) {
    $.mobile.loading("show");
    var tour_id = $(event.target).closest('.selectTour').attr('id');

    this.router.navigate("tour/" + tour_id, {
        trigger: true
    })
},

You can even try e.currentTarget.id if the click handler is targeting the selectTour element.

I think you should change your script little bit this way:

var tour_id = ($(event.target)[0].id.length) ? $(event.target)[0].id : $(event.target).closest('a.selectTour')[0].id;

Because your event.target element is not always selectTour so it does not get you the id of it, so instead as you are using jQuery you can check for the id length if that is available then assign the id of it otherwise if event.target is other than selectTour then traverse up to the selectTour with .closest() the get and assign the id to the var tour_id .


With jQuery's .attr() :

var tour_id = ($(event.target).attr('id').length) ? $(event.target).attr('id') : $(event.target).closest('a.selectTour').attr('id');

This thing gave me 32 which i think is correct

$('.selectTour').bind('click',function(e){
  alert($(this).attr('id'));
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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