Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

html - Jquery change the Element Order

How can I move each label in front of the input element they're next to using jQuery?

<div class="input select classCheckBox">
    <label for="checkboxId">classCheckBoxs</label>
    <input type="hidden" id="checkboxId" value="" name="checkboxName" />
    <br /> 
    <div class="classCheckBox"> 
        <input type="checkbox" id="checkboxId24" value="1" name="checkboxName[]" />
        <label for="checkboxId24">1 </label>
    </div>
    <div class="classCheckBox">
        <input type="checkbox" id="checkboxId25" value="2" name="checkboxName[]" />
        <label for="checkboxId25">2</label>
    </div>
    <div class="classCheckBox"> 
        <input type="checkbox" id="checkboxId26" value="3" name="checkboxName[]" />
        <label for="checkboxId26">3</label>
    </div>
    <div class="classCheckBox">
        <input type="checkbox" id="checkboxId27" value="4" name="checkboxName[]" />
        <label for="checkboxId27">4</label>
    </div>
    <div class="classCheckBox"> 
        <input type="checkbox" id="checkboxId28" value="5" name="checkboxName[]" />
        <label for="checkboxId28">5</label>
    </div>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
$('.select .classCheckBox label').each(function() {
  $(this).insertBefore( $(this).prev('input') );
});

DEMO


A little explain

  • $('.select .classCheckBox label') select each label within each .classCheckBox

  • $(this) within loop point to label

  • .insertBefore() insert any element before the matched element that passed as argument

  • $(this).prev('input') points the input before label

  • so, $(this).insertBefore( $(this).prev('input') ) will insert each label before its previous input


Related refs:


Alternate ways:

$('.select .classCheckBox input').each(function() {
  $(this).insertAfter( $(this).next('label') );
});

DEMO

OR

$('.select .classCheckBox input').each(function() {
  $(this).before( $(this).next('label') );
});

DEMO


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...