问题
I'm not so sharp on jquery but am setting up an analytics implementation (Using Google Tag MAnager) that uses titles.
I have this line:
var linkTitle = $(this).attr('title');
The this in question is a form checkbox and it has no title attribute. The grand parent li, however, does. I'd like to select the grand parent title attribute. Is that possible?
The structure is like so:
<ul>
<li>
<input>
回答1:
you can try like this.
$(this).parent().attr('title');
or you can also do like this.
$(this).parents('li').attr('title');
回答2:
Use the following:
$(this).closest('li').attr('title');
closest()
returns the first element from the ancestors of the $(this)
jQuery node/object which matches the selector (li
) passed to the method, and will then access its title
attribute.
The benefit of using closest()
(in place of parent()
) is that closest()
requires less prior knowledge of the DOM structure, and allows for other ancestors to be inserted between the two (so if the input
is wrapped in a new div
, or fieldset
, it doesn't matter; closest()
will still work).
References:
- attr().
- closest().
回答3:
You can access the parent element via the parent() function.
var linkTitle = $(this).parent().attr('title');
来源:https://stackoverflow.com/questions/18743846/select-grand-parent-element-attribute