2016-06-22 4 views
-1

ボタンをクリックしたときにjavascriptを使用してHTMLページに要素を追加し、このボタンのonclick属性を使って何かを実行するテストとして警告しますこの追加されたボタンがクリックされたときには何も警告しません。ここにコードがあります。javascriptで追加されたhtml要素のアクションを実行する

あなたは二重引用符を使用しているアラートの内部HTML

<!DOCTYPE html> 
<html> 
<head> 
<style> 
    table, th, td { 
     border: 1px solid black; 
     border-collapse: collapse; 
    } 
    th, td { 
     padding: 5px; 
    } 
</style> 
</head> 
<body> 
<div style="display:inline-flex;"> 
<input id="inptext" type="text" placeholder="Your name..."></input> 
<input id="inpadress" style="margin-left: 10px;" id="inptext" type="text" placeholder="Your email..."></input> 
<button onclick="myFunction()"style="margin-left: 10px;" id="box">Add</button> 
</div> 
<br> 
<div style="display: inline-flex"> 
<table id="tablename" style="width:80%; margin-top:15px;"> 
    <tr> 
    <th>Name</th> 
    <th>Email</th> 
    </tr> 
</table> 
<div id="buttons" style="float:right;width: 300px; margin-top:50px;"> 
</div> 
</div> 


<script> 
var z = 1; 
function myFunction() { 
    var x = document.getElementById("inptext").value; 
    var y = document.getElementById("inpadress").value; 
    document.getElementById("tablename").innerHTML = document.getElementById("tablename").innerHTML + '<tr><td>' + x + '</td><td>' + y + '</td></tr>'; 
    document.getElementById("buttons").innerHTML = document.getElementById("buttons").innerHTML + '<button onclick="myFunctionedit()" style="margin-left:8px" class="edit" id="vda' + z + '">Edit</button><button onclick="window.alert("sometext");" style="margin-left:4px" class="deleteit" id="a' + z + '">Remove</button><button style="margin-left:8px" class="update" id="cvda' + z + '">Update</button></div><div id="zzza' + z + '" style="height:10px"></div>'; 
    document.getElementById('cvda'+z).style.visibility = 'hidden'; 
    z = z+1; 
} 
</script> 


</body> 
</html> 

答えて

0

<button onclick="window.alert("sometext");" style="margin-left:4px" class="deleteit" id="a' + z + '"> 

は、単一引用符にそれを変更してみてください:

<button onclick="window.alert(\'sometext\');" style="margin-left:4px" class="deleteit" id="a' + z + '"> 
+0

は、なぜあなたは\入れたのですか? –

+0

ボタンを動的に生成しているので、テキストはすでに別の一重引用符の中に入っています。あなたはそれをエスケープする必要があるので、ブラウザは文字列の最後とはみなしません。 – demarchisd

+0

'\'はエスケープ文字なので、文字列の末尾ではなく文字列の一部として ''を扱います。 – neilsimp1

0
<button onclick="window.alert("sometext");" style="margin-left:4px" class="deleteit" id="a' + z + '">Remove</button> 

は無効なhtmlを作成します。

はその上で

<button onclick="window.alert(\'sometext\');" style="margin-left:4px" class="deleteit" id="a' + z + '">Remove</button> 

を試してみて、#buttonsfloat: right;は、ボタンがunclickableなっています。そのfloatを削除するか、z-indexとしてください。

ワーキングJSFiddle:https://jsfiddle.net/L8ymqLwh/float: right;で除去)

関連する問題