jQuery: child elements of appended object
Is there a more elegant way of working with multiple objects within an object. For example:
<table class="thisTable">
<tr class="thisRow">
<td class="row1"></td>
<td class="row2"></td>
<td class="row3"></td>
</tr>
</table>
Instead of doing:
$("table.thisTable tr.thisRow td.row1").text("Hi")
$("table.thisTable tr.thisRow td.row2").text("Mom")
$("table.thisTable tr.thisRow td.开发者_运维技巧row3").text("Dad")
is there a method that allows:
$("table.thisTable tr.thisRow").function() {
$(this).children("td.row1").text("Hi");
$(this).children("td.row2").text("Mom");
$(this).children("td.row3").text("Dad");
}
I know you don't gain anything functionally, but I have a lot of long selectors that start to get difficult to track and maintain in code.
I've been scouring the jQuery documentation, but the concept isn't jumping out at me and my Google search terms just aren't getting me in the right direction.
$(document).ready(function() {
$('.thisRow').children().each(function(index, obj) {
$(obj).text('Hi');
});
});
Will iterate through the children and allow you to address each element individually. Also, .children() only goes down one leve, where .find() will traverse multiple levels of the DOM (in case your example gets larger in practice).
One thing you can do is cache the main selector as a variable:
var $tr = $("table.thisTable tr.thisRow");
$tr.find('td.row1').text('Hi');
$tr.find('td.row2').text('Hi');
$tr.find('td.row3').text('Hi');
Or you can group them and provide a context:
$('td.row1, td.row2, td.row3', 'table.thisTable tr.thisRow').text('Hi');
Just use:
$("table.thisTable tr.thisRow td.row1").text("Hi");
This will select all tds under your .thisRow
row and set their text in one line.
$('.thisRow td').text('Hi');
For reference, classes are for grouping elements together. You are using the class as an id, which individually identifies each element with a unique name. The selector works similarly to selectors in CSS if you are familiar with CSS.
Your question is a little vague, and I'm guessing it's because you don't know precisely what to ask. But I think what you're looking for is the $.each()
function, in addition to @Alex's answer.
$("table.thisTable tr.thisRow").children().each(function() {
// "this" is the current child of tr.thisRow
$(this).text('Hi!');
});
Update
In response to your comment: You have to remember that jQuery selectors are just strings, and therefore you can do anything you want to generate them. I do things like this all the time:
var base_selector = 'table#my-id tr.my-row-class '; // notice the space
$(base_selector + 'td.something').css('backgroundColor', 'red');
精彩评论