Hi All if i assign an attribute to list like this:开发者_如何学C
<ul type_code=27>
how can i get this value(ul type_code value ) if i know that the id of li=10(<li id=10>
)?
Try this also:
var code = $('#li-id').closest('ul').attr('type_code');
Please note: the "10" as the value of id attribute may not work on other browser.
The ID you give ("10()") is an invalid ID attribute (IDs can't start with a digit). Sorry, IDs used with CSS can't start with a digit; HTML ones can if you're not going to use them with CSS. But with jQuery, you use CSS selectors a lot, so best to stick to the CSS rules.
[Edit: I was using parents
, but closest
is better because it stops looking as soon as it's found the first match. Please upvote jerjer for that.]
In any case, let's say the LI has the ID "fred":
var code = $("#fred").closest("ul").attr("type_code");
E.g., with this HTML:
<ul type_code=27>
<li id='fred'>...</li>
</ul>
...the above code will set code
to "27". Live example
Note, though, that creating your own attribute values means your HTML won't validate. It's a popular practice, though, so much so that it's specifically catered for now in HTML5: Any attribute with the prefix data-
will validate. So updating the above:
HTML:
<ul data-type-code=27>
<li id='fred'>...</li>
</ul>
JavaScript w/jQuery:
var code = $("#fred").closest("ul").attr("data-type-code");
Live example
精彩评论