2017-01-02 85 views
0

我有一个复选框,其上有一个图像替换。我想要做的是点击复选框并获取图像的src属性值并将其放置在textarea中。如何在复选框单击后获取src属性值?

HTML

<div class="thumbnail"> 
    <input type="checkbox" name="thing_5" value="valuable" id="thing_5"> 
    <label for="thing_5"> 
    <img class="img-responsive" src="https://upload.wikimedia.org/wikipedia/commons/a/ac/U.S._Marines_in_Operation_Allen_Brook_(Vietnam_War)_001.jpg"> 
    </label> 
</div> 
<textarea id='txtarea'></textarea> 

jQuery的

var tempValue = ''; 
$('.thumbnail :checkbox').change(function() { 
    tempValue += $(this).nextAll("img").attr("src"); 
    $('textarea').html(tempValue);   
}); 

CSS

textarea{width:100%;height:200px;} 
input[type=checkbox] { 
    display: none; 
} 

input[type=checkbox] + label { 
    background: #999; 
    display: inline-block; 
    padding: 0; 
} 

input[type=checkbox]:checked + label { 
    border: 10px solid grey; 
    padding: 0; 
} 

此刻我得到在textarea之内的3210。

的jsfiddle

http://jsfiddle.net/vWFQQ/33/

+0

像这样:http://jsfiddle.net/vWFQQ/39/ –

回答

3

.nextAll()不会工作,因为,它是<label>内。您需要使用.next().find()

tempValue += $(this).next("label").find("img").attr("src"); 

片段

$(document).ready(function() { 
 
    var tempValue = ''; 
 
    $('.thumbnail :checkbox').change(function() { 
 
    tempValue += $(this).next("label").find("img").attr("src"); 
 
    $('textarea').html(tempValue); 
 
    }); 
 
});
textarea { 
 
    width: 100%; 
 
    height: 200px; 
 
} 
 

 
input[type=checkbox] { 
 
    display: none; 
 
} 
 

 
input[type=checkbox] + label { 
 
    background: #999; 
 
    display: inline-block; 
 
    padding: 0; 
 
} 
 

 
input[type=checkbox]:checked + label { 
 
    border: 10px solid grey; 
 
    padding: 0; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="thumbnail"> 
 
    <input type="checkbox" name="thing_5" value="valuable" id="thing_5"> 
 
    <label for="thing_5"> 
 
    <img class="img-responsive" src="https://upload.wikimedia.org/wikipedia/commons/a/ac/U.S._Marines_in_Operation_Allen_Brook_(Vietnam_War)_001.jpg"> 
 
    </label> 
 
</div> 
 
<textarea id='txtarea'></textarea>

+0

为什么downvote?有什么理由? –

+0

嘿谢谢,我会在一分钟内接受它。无论如何,我可以在textarea中添加/删除选中的项目吗?如果我有更多图像/复选框,例如http://jsfiddle.net/vWFQQ/40/ –

+0

@ rob.m,该怎么办?您可能需要重做整个循环。这是最好的方法。你想要一个不同的解决方案吗? –