根据用户输入替换而不是追加?

时间:2014-01-06 20:26:37

标签: javascript input replace

此功能目前适用于在div中附加img。但是我需要一个替换方法而不是多个img div堆叠在一起。

我也对jQuery中的解决方案持开放态度。

function getImg(){

    var url=document.getElementById('txt').value;
    var div=document.createElement('div');
    var img=document.createElement('img');

    img.className="img-responsive";

    img.src=url;

    div.appendChild(img);

    document.getElementById('gif-btn').innerHTML=""; <!-- Correct answer -->
    document.getElementById('gif-btn').appendChild(div);

    return false;
}

提前感谢您提供任何帮助。非常感谢!

2 个答案:

答案 0 :(得分:2)

在你追加之前,你可以清除div,然后添加新的

function getImg(){

    var url=document.getElementById('txt').value;
    var div=document.createElement('div');
    var img=document.createElement('img');

    img.className="img-responsive";

    img.src=url;

    div.appendChild(img);

    document.getElementById('gif-btn').innerHTML = ""; // <-- Clears the gif-btn div
    document.getElementById('gif-btn').appendChild(div);

    return false;
}

答案 1 :(得分:0)

使用jQuery

var url = $("#txt").val();
var image = $("<img>").attr("src", url).addClass("img-responsive");
var container = $("<div></div>");

// add the image to the <div> container
container.append(image);
// set the contents of gif-btn
$("#gif-btn").html(container);

......或者更好的是,你可以做一个简单的淡出,淡入......

// replace the last line with this
$("#gif-btn").fadeOut("fast", function() { 
  $("#gif-btn").html(container); $("#gif-btn").fadeIn(); 
});
相关问题