2017-07-12 16 views
0

ボタンを作成する必要があるため、ボタンを作成する必要があります.Javascriptを使用してボタンを作成しようとしています。 機能を持つボタンは1つにする必要がありますが、作成するボタンは別のボタンで作成する必要があります。特定のdivにボタンを追加する

どうすればよいですか?

以下に示す私のアイデアは機能しません。

function createButton(context, func){ 
 
    var button = document.createElement("input"); 
 
    button.type = "button"; 
 
    button.value = "im a button"; 
 
    button.onclick = func; 
 
    context.appendChild(button); 
 
}
html,body { margin:0; padding: 0; } 
 
#inputpanel { 
 
    width: calc(40vw - 10px); 
 
} 
 
#selectpanel { 
 
    width: calc(20vw - 10px); 
 
} 
 

 
#inputpanel,#selectpanel { 
 
    display: inline-block; 
 
    box-sizing: border-box; 
 
    height: calc(100vh - 200px); 
 
    margin: 0; 
 
    padding: 0; 
 
}
<div id="inputpanel"> 
 
    
 
<button type="button" id="createBut" onclick="createButton(document.selectpanel, function(){ 
 
    alert('it works');})">create Button</button> 
 
</div> 
 

 
<div id="selectpanel"> 
 
adsadasdasd<br /> 
 
asfdsdfsdfgdf 
 

 
</div>

おかげエイドリアンここ

+0

のdocument.createElement( 'ボタン')を使用します。 –

+0

'document.selectpanel'は存在しません。適切な既存の要素参照を渡すか、要素idを文字列として渡すだけで、関数内でgetElementByIdを使用して要素を取得できます。 – CBroe

答えて

1

は、ボタンを作成するためのコードです:

function createButton(context, func) { 
 
    var button = document.createElement("input"); 
 
    button.type = "button"; 
 
    button.value = "im a button"; 
 
    button.onclick = func; 
 

 
    var selectPanel = document.getElementById('selectpanel'); 
 
    selectPanel.appendChild(button); 
 
}
html, 
 
body { 
 
    margin: 0; 
 
    padding: 0; 
 
} 
 

 
#inputpanel { 
 
    width: calc(40vw - 10px); 
 
} 
 

 
#selectpanel { 
 
    width: calc(20vw - 10px); 
 
} 
 

 
#inputpanel, 
 
#selectpanel { 
 
    display: inline-block; 
 
    box-sizing: border-box; 
 
    height: calc(100vh - 200px); 
 
    margin: 0; 
 
    padding: 0; 
 
}
<div id="inputpanel"> 
 

 
    <button type="button" id="createBut" onclick="createButton(document.selectpanel, function(){ 
 
    alert('it works');})">create Button</button> 
 
</div> 
 

 
<div id="selectpanel"> 
 
</div>

0

私はこの問題は、WHEに位置していると思いますあなたはボタン変数を宣言しています。

それは次のようになります。

var button = document.createElement('input'); 

の代わりに:

var button = document.selectpanel.createElement('input'); 
+0

そうですね、私はそれを修正しました。 – DaPole

関連する問題