写下“src"属性

Write the "src" attribute when I click a image

本文关键字:属性 quot src 写下      更新时间:2023-09-26

我有这个代码通过谷歌图像API进行图像搜索:

$(document).ready(function(){
        $('#envio').click(function(){
            var iURL = "http://ajax.googleapis.com/ajax/services/search/images";
            $.ajax({
                url: iURL,
                type: 'GET',
                dataType: 'jsonp',
                data: {
                    v:  '1.0',
                    q:  $('#query').val(),
                    format: 'json',
                    jsoncallback:  '?'
                },
                success: function(data) {
                    console.log(data);
                    var html = '';
                    var j = 1;
                    $.each(data.responseData.results, function(i, v) {
                        html += '<img id="' + j + '" src="' + v.tbUrl + '" title="' + v.title + '" alt="' + v.title + '"/>';
                        j++;
                    });
                    $('body').append(html);
                },
                error: function(xhr, textStatus, error){
                    console.log(xhr.statusText, textStatus, error);
                }
            });                
        });
    });

我有一个INPUT字段,需要当我点击一个IMG SRC属性的值去那里。我尝试用这段代码,但没有工作:

$('img').click(function(){
    $.each(function(){
        $('#urlimagen').val($this.src);
    });
});

默认情况下,第一个代码只返回4个图像,我需要超过4个,然后我的问题围绕这段代码如下:

  1. 有没有人知道如何获得超过4个图像?
  2. 可以帮助我修复图像代码吗?我的意思是,当我点击图像时,SRC值必须在INPUT中称为# unlimagen。

我会改变你用来附加你的图像的代码,并确保你分配点击事件句柄在那个时候,而不是之前。

$.each(data.responseData.results, function(i, v) {
    var $img = $('<img />'); // create a new image object
    // change image attributes
    $img.attr({
        'id': 'j',
        'src': v.tbUrl,
        'title': v.title,
        'alt': v.title
    });
    j++;
    // append image to DOM, remove your append statement and leave this here
    $('body').append( $img );
    $img.click( function () {
        $('#urlimagen').val( $(this).attr('src') );
    });
});

对于返回的4个图像,查看您的代码似乎取决于data.responseData.results对象的长度,我不知道您是否可以修改返回的数量。

如果你的html看起来像这样:

<img src="..." class="clickableImage" />

. .然后你可以使用以下javascript:

$('.clickableImage').click(function(){
    $('#urlimagen').val($(this).attr('src');
});

将所单击图像的src属性放入id为urlimagen的输入框中。

$('.clickableImage')选择器获取类名为clickableImage的所有元素。.click为每个元素添加了一个click事件。在函数内部,$(this)将引用被单击的图像。使用attr方法,检索所单击图像的src属性,并使用val方法将其设置为表单输入的值。

如果你不能或不想添加类名,你可以通过使用选择器$('img')使其适用于所有图像,但我真的建议你使用一个类名,如果可能的话,这样你就可以控制哪些图像涉及。

现在,如果您希望每个被单击的图像的值都是,将添加到输入值中,而不是替换它,请使用以下命令:
$('#urlimagen').val($('#urlimagen').val() + ($('#urlimagen').val() > 0 ? ',' : '') + $(this).attr('src');

你点击的每一张图片都将添加一个新项目到列表中。

想要一个数组吗?html:

<form id="urlimages"></form>

. .使用以下脚本:

$('#urlimages').append('<input type="hidden" name="images[]" value="'+$(this).attr('src')+'" />');

在服务器端,POST将包含每个单击的图像的数组。

$('img').click(function(){
        $('#urlimagen').val($(this).attr("src"));
});