2015-06-14 61 views
0

下面的代碼是一個簡單的表單,它接受來自用戶的數字並顯示在表單中輸入的半徑的圓。一切工作都很好,只是當我點擊提交按鈕時,圓圈就消失了。如何解決這個問題?我點擊提交按鈕後,我希望該圈子在那裏很久。使用SVG在html頁面中顯示動態圓圈

<title>Dynamic Vector Circle</title> 

<script type="text/javascript"> 

    var svgNS = "http://www.w3.org/2000/svg"; 

    function createCircle() 
    { 
     var myCircle = document.createElementNS(svgNS,"circle"); //to create           a circle, for rectangle use rectangle 
     var radius= document.getElementById("rad").value; 
     myCircle.setAttributeNS(null,"id","mycircle"); 
     myCircle.setAttributeNS(null,"cx",100); 
     myCircle.setAttributeNS(null,"cy",100); 
     myCircle.setAttributeNS(null,"r",radius); 
     myCircle.setAttributeNS(null,"fill","black"); 
     myCircle.setAttributeNS(null,"stroke","none"); 

     document.getElementById("mySVG").appendChild(myCircle).innerHTML; 
    }     

</script> 

<form> 
    <input type="text" id="rad" placeholder="Enter radius"> 
    <button onClick="createCircle();">Submit</button> 

    <svg id="mySVG" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> 
</svg> 

</form> 

+0

我沒有看到JSFiddle的這種行爲:http://jsfiddle.net/252yLdqx/ – Cymen

+0

@Cymen,你的代碼不在'form'裏面,就像在OP – Grundy

+0

@Grundy好點! – Cymen

回答

1

問題是單擊按鈕上的表單的默認操作是提交。爲了避免提交,您可以從綁定到該按鈕的功能return false。因此,如果您將createCircle的末尾更改爲:

... 
    return false; 
} 

它會按照您的期望工作。這裏是整個函數:

function createCircle() 
{ 
    var myCircle = document.createElementNS(svgNS,"circle"); //to create           a circle, for rectangle use rectangle 
    var radius= document.getElementById("rad").value; 
    myCircle.setAttributeNS(null,"id","mycircle"); 
    myCircle.setAttributeNS(null,"cx",100); 
    myCircle.setAttributeNS(null,"cy",100); 
    myCircle.setAttributeNS(null,"r",radius); 
    myCircle.setAttributeNS(null,"fill","black"); 
    myCircle.setAttributeNS(null,"stroke","none"); 

    document.getElementById("mySVG").appendChild(myCircle).innerHTML; 

    return false; 
} 

的jsfiddle:http://jsfiddle.net/252yLdqx/2/

或者你可以改變buttontype="button"input將不會有默認行爲提交表單:

<input type="button" id="create" value="Create"/>

JSFiddle:http://jsfiddle.net/252yLdqx/3/

或者你可以改變buttontype="button"覆蓋默認type="submit"像這樣:

<button type="button" onClick="createCircle();">Submit</button>

或者你也可以不form標籤內封閉並做你想!

+0

'

+0

它在JSFiddle中工作正常。但是,當我在Chrome瀏覽器中打開.html文件時,該圓圈不會呈現。你能提出什麼可能是沒有渲染的問題? –

+0

@Grundy謝謝 - 我會補充一點。 – Cymen