jQuery select just the first one
My javascript
$(".controls").click(function(event) {
var div = $(event.target).parents(".controls");
var a = $(div).find("tr .select");
return false;
});
And html
<div id="grid1" class="controls">
<a href="/projekt/create">Add</a>
<a href="/projekt/edit">Edit</a>
<开发者_运维技巧;/div>
<div id="grid2" class="controls">
<a href="/uloha/create">Add</a>
<a href="/uloha/edit">Edit</a>
<table>
<tr id="1"></tr>
<tr id="2" class="select"></tr>
<tr id="3"></tr>
</table>
</div>
I'd like to select the first TR which has class select
.
I've tried
var a = $(div).find("tr:first .select");
or
var a = $(div).find("tr .select:first");
but none of them worked.
You could try this:
var a = $("tr.select", div).first();
or
var a = $("tr.select:first", div);
Since there's :first and first().
To select all of this within that you use:
$(this, that)
Would something like this work?
$(".controls").click(function(event) {
var a = $("tr.select:first", ".controls");
// do stuff with a....
return false;
});
This changes "two" to okay, but not 'four" when you press the button.
<div class="controls">
<input type="button" value="Click the control" />
</div>
<div id="grid2" class="controls">
<table>
<tr id="1"><td>one</td></tr>
<tr id="2" class="select"><td>two</td></tr>
<tr id="3"><td>three</td></tr>
<tr id="4" class="select"><td>four</td></tr>
</table>
</div>
<script type="text/javascript">
$(".controls input").click(function(event) {
var a = $("tr.select:first", ".controls");
$(a).text("okay");
return false;
});
</script>
(As a side note, those are not proper id names, they cannot start with a number if you want valide html)
I'm pretty sure what you want is this:
var a = $(div).find("tr.select:first");
In jQuery selectors, spaces separate levels in the hierarchy.
If I used the selector "tr:first .select"
it would look in the first tr and return all children that have the select class.
If I used the selector "tr .select:first"
it would look in every tr
and return the first child element with the select class for each tr
.
You can use the first() function to do that.
var a = $(div).find("tr.select").first();
What about using the index?
var a = $(div).find("tr.select")[0]
/* I think that's the right syntax */
精彩评论