2014-01-06 4 views
1

이 함수는 현재 div에 img를 추가하는 데 사용됩니다. 하지만 여러 img div가 서로 위에 쌓이는 대신 replace 메서드가 필요합니다.사용자 입력에 따라 추가 대신 바꾸시겠습니까?

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; 
} 

미리 도움을 청하십시오. 매우 감사! 당신이 추가하기 전에

+0

새 이미지를 추가 한 후에 이전 이미지를 제거하면됩니다. – Barmar

+0

실제로 javascript에서 청구서에 맞는 'replaceChild' 메소드가 있습니까? – adeneo

+1

'.appendChild()'를'.innerHTML = 'stuff''로 변경하십시오. – SenorAmor

답변

2

, 당신은 더 좋은 아직 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); 

... 또는를 사용하여 새

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

이것은 작동합니다! 더 중요한 것은, 그것은 의미가 있습니다. 배우기! – dMaller

0

을 추가, 사업부를 지울 수 있습니다, 당신은 간단한 페이드를 할 수 꺼짐, 페이드 인 ...

// replace the last line with this 
$("#gif-btn").fadeOut("fast", function() { 
    $("#gif-btn").html(container); $("#gif-btn").fadeIn(); 
}); 
관련 문제