我有一个奇怪的问题......我想。
我有以下代码:
在<body>
:
<!-- headers, includes and other "plain" html... -->
<div class="col-sm-4"> <!-- Second column -->
World!
<br>
<p id="testerP"></p>
<script>
var temptext = '';
for (var i = 0 ; i < 3 ; i++){
temptext += '<button name="deleted" value=' + i + ' class="btn btn_sm btn-danger deletes" role="button">DEL</button><br>'
temptext += '<br>';
temptext += '<br>';
}
document.getElementById("testerP").innerHTML = temptext;
</script>
</div>
<div class="col-sm-4"> <!-- Third column -->
<h2>Robot Job Queue</h2>
<table id="queueAll" class="table table-striped table-responsive">
<thead><tr><th>Id</th><th>Type</th><th>Delete</th><th>Priority</th></tr></thead>
<tbody id="tbod">
</tbody>
</table>
</div>
在</body>
<script>
$(document).ready(function () {
var socket = io();
// When the client receives a "queue" from the server
socket.on('queue', function(msg){
var html = '';
var tmp = '';
html += '';
temptext = '';
if(msg.length == 0){$("#queueAll").hide();}
else{$("#queueAll").show();}
for (var i = 0 ; i < msg.length && i<5 ; i++){
html += '<tr name="queueRow">'
html += '<td>' + msg[i]['id'] + ' </td>'
html += '<td>' + msg[i]['type'] + '</td>'
tmp = '<button name="deleted" value=' + msg[i]['id'] + ' class="btn btn_sm btn-danger deletes" role="button">DEL</button>';
html += '<td>' + tmp + '</td>'
html += '<td>' + msg[i]['priority'] + '</td>'
html += '</tr>'
}
document.getElementById("tbod").innerHTML = html;
});
//Submitting deleteJob
$('.deletes').on('click',function(e){
console.log(e.target.value);
var dataReturn = {jobType:e.target.value};
socket.emit("delete job",dataReturn);
});
});
</script>
问题是:
第一个for循环(<body>
内的id = testerP的那个)按预期运行。我在服务器端和客户端都获得了按钮值。
但是,当我点击表格内的按钮时,我什么都没有反应?!?!
我可以使用
获取“testerP”按钮$('button[name="deleted"]').on('click',function(){...
$('.deletes').on('click',function(){...
和
$('button').on('click',function(){...
但表格按钮没有任何反应!
为什么不(稍微哼)???
项目信息:
答案 0 :(得分:2)
问题可能是没有将代码包装在DOM中。
$(document).ready(function() {
$(document).on('click', 'button[name="deleted"]', function(event) {});
$(document).on('click', '.deletes', function(event) {});
});
答案 1 :(得分:2)
动态添加到DOM的元素,在你的情况下生成删除按钮的for循环需要用
来解决$(document).on('click', '.deletes', function() {
// your delete logic
});