开发者

Is it possible to set the width of an element to that of the preceding element?

My input elements are followed by a div. I would like to set the width of that div to be that of the preceding input element.

<input type="text" class="input" size="100" name="data"/>
<div class="inputHelp"> enter data above </div>

<input type="text" class="input" size="80" name="moredata"/>
<div class="inputHelp"> enter more data above </div>

In each 开发者_如何学JAVAinstance, the class .inputHelp should have the same width as the input element before it.

Using the next selector, I was able to grab the width of input elements followed by the inputHelp div. However, when attempting to set the width of the following inputHelp div, it instead set the width of ALL inputHelp divs on the page. How can I limit it to only set the width of the next inputHelp, and then iterate through all the other input + inputHelp combinations on the page?

Here's my current JQuery code:

$('.input + .inputHelp').width( $('.inputHelp').prev('.input').width() );


$('.input + .inputHelp').each(function() {
    $(this).width($(this).prev('.input').width();
});

The key to the solution is using $(this), rather than $('.inputHelp'). The latter grabs all .inputHelps globally, rather than the specific one you are looping on.


I wonder, is the .each solution needed - I'm just going to fire up my dev environment and test - more just a curiousity of mine as you've already marked Stuart B's answer correct (which it is).

Would the following not be equivalent:

$('.input + .inputHelp').width( $(this).prev('.input').width() );

I'll update this with a comment when I've tinkered, but as someone learning jQuery myselft, I'd love to hear if they're equivalent and if not why.

Thanks, Terry

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜