How to simplify this jQuery expression?
$country.parent().parent().next().children('td').children('.province-select')
Basically I have some HTML that looks like this:
<table>
<tr>
<th>country</th>
<td><select name="country"/></td>
</tr>
<tr>
<th>province</th>
<td><select class="province-select"/></td>
</tr>
</table>
Once I've nabbed the country select
, I need to find the next .province-select
. Would be nice if it's little more robust to subtle HTML changes.
AFAIK next()
only finds siblings, and closest()
only traverses up the DOM tree.
I have a few of these all in the same table. That's why I'm using all this parent/next garbage. I don't want to use IDs because... well, then the script will only work on one s开发者_如何转开发pecific country/province pair; I need it to run on all of them; thus I need to find the corresponding province field for the country field.
For example:
$contry.closest('tr').next('tr').find('> td > .province-select')
You could try
$country.parents( 'tr' ).next().find('.province-select')
Below is ugly but will account for 'subtle' changes like adding extra tr's in between the two selects, it also accounts for multiple country/province pairs of select elements.
//cache closest tr so we can get its index and use it as the base for the next traversal
var $closesttr = $country.closest('tr');
//search the tbody for the first instance of an element that has the class
// province-select and is after the tablerow that contains the current country
$closesttr.parent()
.find('tr:gt(' + $closesttr.index() + ') .province-select:first');
I would probably go with:
$country.closest('table').find('.province-select');
if you can add IDs to your selects
$('#country')
and $('#province-select')
will get your elements, that's assuming your HTML isn't inside a repeater/list of some kind
Edit:
hmm, in that case have you tried the equivalent of GetElementsByName?
精彩评论