开发者

jQuery selectors - parental problems

I have an emote selector that opens up when a user clicks an entry in a diary. The way I've worked it is that the emote selector panel lives hidden at the top of the page. When a user clicks on the 'emote control' associated with an entry, I use JavaScript to grab the HTML of the emote selector panel from the top of the page and insert it next to the entry.

Using Firebug, here's what the finished product would look like in the page (snippet from element inspect). I'm trying to get the ID for the class 'emote-control-container' which contains the entry id:

<td>
    <div id="1467002" class="emote-select emote-default">&nbsp;</div>
    <div class="emote-control-container" id="emote-controls-1467002">
    <div id="emote-control-selector">
        <div id="emote-control-selector-body">
            <ul>
                <li id="emote-1"><img src="/images/default_emote.gif?1276134900" class="emote-image" alt="Default_emote"></li>
                <li id="emote-2"><img src="/images/default_emote.gif?1276134900" class="emote-image" alt="Default_emote"></li>
                <li id="emote-3"><img src="/images/default_emote.gif?1276134900" class="emote-image" alt="Default_emote"></li>
                <li id="emote-4"><img src="/images/default_emote.gif?1276134900" class="emote-image" alt="Default_emote"></li>
            </ul>
        </div>
        <div id="emote-control-selector-footer">
            &开发者_StackOverflow社区amp;nbsp;
        </div>
    </div>
</div>
                    </td>

I need the entry ID along with the emote ID to make a post via AJAX when a user selects an emote from the selector panel by clicking on it.

I'm able to get the emote ID just fine with this, which I'm using to alert-out the selected emote ID:

  jQuery('li').live('click', function(e) { 
    e.preventDefault;
    var emoteId = this.id;
    alert(emoteId);
  });

I'm having trouble traversing up DOM to get the element ID from '.emote-control-container.

I've tried everything, but I'd expect this to work, but it doesn't:

  jQuery('li').live('click', function(e) { 
    e.preventDefault;
    var entryId = jQuery(this.id).parent(".emote-control-container").attr("id");
    alert(entryId);
  });

What am I doing wrong.? I can't target the ID of the .emote-control-container.


You want .closest() here, like this:

jQuery('li').live('click', function(e) { 
  e.preventDefault;
  var entryId = jQuery(this).closest(".emote-control-container").attr("id");
  alert(entryId);
});

The .parent(selector) call only gets the immediate parent if it matches the selector, it doesn't keep going up until it finds it (which is a bit counter-intuitive). .closest(selector) does climb until it matches the selector, which is what you're after.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜