从所选图像中提取SRC,以逗号分隔

I'm using a Wordpress plugin where I can only type attachment urls (comma separated) in an input box. I need to alter the code so I can click an image and it will extract the src to put it in the input box.

I made it possible with only one image.

First, I echo'd all the images from my media library. And then I did this:

    <img class="media-image" src="<?php echo $images[$i]; ?>"/>
    <script type="text/javascript">
    jQuery(document).ready(function() {
        jQuery('.media-image').click(function(){
            var thisValue = jQuery(this).attr('src');
            var thisTarget = jQuery('#target');
            thisTarget.val(thisValue);
            return false;
        });
    });
    </script>

    <input id="target" type="text"></input>

What this does: Whenever I click an image, the src will be put in the input text box. When I click another image, the value will be changed accordingly.

But how can I achieve this with multiple images? So, if I click 3 images, I want all the src's to be comma separated in the input field. Whenever I click a selected image again, I want it to be deselected (i.e. I want the src to be removed from the input).

Track the clicked/de-clicked images in an array and join it to form a string value for your input. Something like:

var imgs_tracker = [], field = jQuery('#target');
$('body').on('click', '.media-image', function() {
    var src = $(this).attr('src'), already_in = imgs_tracker.indexOf(src);
    already_in == -1 ? imgs_tracker.push(src) : imgs_tracker.splice(already_in, 1);
    field.val(imgs_tracker.join(', '));
});

Note also I delegate the click event - much more efficient than binding it to each and every item.

<img class="media-image" src="<?php echo $images[$i]; ?>"/>
<script type="text/javascript">
jQuery(document).ready(function() {
    jQuery('.media-image').click(function(){
        var thisValue = jQuery(this).attr('src');
        var thisTarget = jQuery('#target');
        thisTarget.val(thisTarget.val() + "," + thisValue);
        return false;
    });
});
</script>

<input id="target" type="text"></input>

Select the previous value and append to it.

$(function () {
    var images = $(".media-image");

    images.on("click", function () {
        var img = $(this),
            selected = !!img.data("selected");

        img.data("selected", !selected);

        var foo = images.filter(function () {
                      return !!$(this).data("selected");
                  }).map(function (_, el) {
                      return this.src;
                  }).get();

        $("#target").val(foo.join());
    });
});

fiddle