如何更改已动态添加到div的图像的源URL?

时间:2013-02-13 06:15:47

标签: javascript html

我有一个div,我在其中动态添加图像。

div.append('<img class="prod48" src="' + url + '" />');

现在url由文本框的focusout设置,具体取决于文本框中的文本。由于附加功能会继续附加,我应该如何更改此url而不在div附加另一张图片?第一次focusout被调用时,我应该能够追加和休息时间更新网址。

4 个答案:

答案 0 :(得分:3)

如果要在将图像元素添加到文档后更新它,您必须有一些方法来引用它。

立即想到几个想法:

  1. 为图像指定唯一ID,然后使用:

    # First, change the html to include an id
    div.append('<img id="abcdef1234" class="prod48" src="' + url + '" />');
    
    #...
    # Later, grab the image by its id and change the source url
    var img = document.getElementById('abcdef1234');
    img.src = newUrl;
    
  2. 或者,第一次动态构造图像,并将元素保存在变量中:

    # First, create an element, and hold it in a variable:
    var img = document.createElement('img');
    img.className = "prod48";
    img.src = url;
    # Now append it to the div:
    div.append(img);
    
    #...
    # Later, we still have that element, so we can just change the source URL:
    img.src = newUrl;
    

答案 1 :(得分:2)

HTML:

<input type="text" id="url">
<div id="image_div">
    Will append image tag to this :     
</div>

JQUERY:

$(document).ready(function(){
$('#image_div').html("<img src='' class='prod48'>");       //will replace image
    $('#url').change(function(){        
        $('.prod48').attr('src',$('#url').val());
    });
});

JSFiddle:here

答案 2 :(得分:0)

为图片提供ID,此代码可以帮助您..

$("img").attr("src", "/img/circleGraph/circle");

答案 3 :(得分:0)

如果你使用的是jQuery,你可以这样做:

var div = $('div');

div.append("<img src='"+url+"' />");

div.find("img").attr("src", newUrl);
相关问题