将不同的属性添加到相同的元素jquery

时间:2013-09-16 12:50:06

标签: javascript jquery

我有这样的事情:

<div class="controls">
<label class="checkbox inline">
<input type="checkbox" value="Boardroom" name="Form[257][]">&nbsp;Boardroom</label>
<label class="checkbox inline">
<input type="checkbox" value="Theatre" name="Form[257][]">&nbsp;Theatre</label>
<label class="checkbox inline">
<input type="checkbox" value="School" name="Form[257][]">&nbsp;School</label>
<label class="checkbox inline">
<input type="checkbox" value="U-shape" name="Form[257][]">&nbsp;U-shape</label>
<label class="checkbox inline">
<input type="checkbox" value="Coctail" name="Form[257][]">&nbsp;Coctail</label>
<label class="checkbox inline">
<input type="checkbox" value="Banquet" name="Form[257][]">&nbsp;Banquet</label>
</div>

我想添加图片,所以它变成这样:

<div class="controls">
<label class="checkbox inline">   
<input type="checkbox" value="Boardroom" name="Form[257][]">
<img src='1.png'>&nbsp;Boardroom</label>
<label class="checkbox inline">
<input type="checkbox" value="Theatre" name="Form[257][]">
<img src='2.png'>&nbsp;Theatre</label>
<label class="checkbox inline">
<input type="checkbox" value="School" name="Form[257][]">
<img src='3.png'>&nbsp;School</label>
<label class="checkbox inline">
<input type="checkbox" value="U-shape" name="Form[257][]">
<img src='4.png'>&nbsp;U-shape</label>
<label class="checkbox inline">
<input type="checkbox" value="Coctail" name="Form[257][]">
<img src='5.png'>&nbsp;Coctail</label>
<label class="checkbox inline">
<input type="checkbox" value="Banquet" name="Form[257][]">
<img src='6.png'>&nbsp;Banquet</label>
</div>

基本上,我需要添加不同的图像foreach标签。任何人都知道如何做到这一点?提前感谢您的回复。

4 个答案:

答案 0 :(得分:1)

尝试一个简单的

$('.controls label input').after(function(idx){
    return '<img src="' + (idx + 1) + '.png" />';
})

演示:Fiddle

答案 1 :(得分:1)

为每个输入定义data-img="/1.jpg",并使用此jquery代码:

$('.controls .checkbox input').each(function()
{
    $(this).after( '<img src="' + $(this).data('img') + '" />' );
});

示例:

<label class="checkbox inline"><input data-img="/images/1.jpg" type="checkbox" value="Boardroom" name="Form[257][]">&nbsp;Boardroom</label>

答案 2 :(得分:0)

var images = ['1.png', '2.png', ...];
$('input:checkbox').each( function( idx, el ) {
    $( el ).after( "<img src='" + images[(idx + 1)] + " />" );
} );

答案 3 :(得分:0)

你可以查看这段代码吗

Demo

$('.controls label input').each(function(cnt){
    $('<img src="' + (cnt + 1) + '.png" />').insertAfter(this)
})