This one has really got me confused:
I have a group of 'items' and I want to select the first <pre>
in each group.
<div class="item">
<table>
<tr>
<td>
<h1>Test</h1>
<pre>0</pre>
<pre>
<code>1</code>
</pre>
<pre>
<code>2</code>
</pre>
</td>
</tr>
</table>
</div>
<div class="item">
<pre>
<code>3</code>
</pre>
<pre&g开发者_运维问答t;
<code>4</code>
</pre>
</div>
<div class="item">
<pre>
<code>5</code>
</pre>
</div>
<div id="output"></div>
My jQuery code looks like this:
$('.item:has(pre)').each(function(){
text = $(this).filter('pre').html()
.replace(/</g,'<').replace(/>/g,'>') + "<br><br>";
$('#output').append(text);
});
I expect the output to be the contents of the <pre>
blocks, but instead, I get nothing. If I use the .size()
function on the matched elements, I get 0 every time.
The above code can be found on jsFiddle: http://jsfiddle.net/george_edison/syLMD/8/
$('div.item pre:first-of-type').each(function(){
text = $(this).filter('pre').html().replace(/</g,'<').replace(/>/g,'>') + "<br><br>";
$('#output').append(text);
});
.filter()
only looks at the current set of elements, whereas .find()
looks at the descendants.
$('.item:has(pre)').each(function(){
text = $(this).find('pre:first').html().replace(/</g,'<').replace(/>/g,'>') + "<br><br>";
$('#output').append(text);
});
精彩评论