我在动态生成的表格中创建一个可点击的按钮很困难,该按钮会发送特定于单击的表格单元格的数据。
只要用户使用此AJAX调用键入搜索框,就会生成并修改我的表格:
$(document).ready(function(){
$("#data").keyup(function () {
$.ajax({
type: "POST",
dataType: "JSON",
data: "data=" + $("#data").val(),
url: "search1.php",
success: function(msg){
var output = "";
for(var i = 0; i < msg.length; i++) {
output += '<tr onmouseover=this.style.backgroundColor="#ffff66"; onmouseout=this.style.backgroundColor="#F0F0F0";>';
output += '<td>';
if (msg[i].website != ''){ output += '<a href = ' + msg[i].website + ' target = "_blank">' + msg[i].name + '</a></td>';}
else output += msg[i].name + '</td>';
output += '<td class="description">' + msg[i].description + '</td>';
output += '<td><input type="button" onclick=' + submit() + ' value=' + msg[i].id + '></td></tr>'; // Here is where I'd like to put in a clickable button
}
$("#content").html(output);
$("#myTable").trigger("update");
}
});
});
});
如果我submit()
只是alert("hello")
,则会在onclick
submit()
{{1}}来电的每个实例加载页面时运行{{1}}。有人可以向我解释如何提交仅在单击按钮时调用,而不是在页面加载时调用。提前谢谢。
答案 0 :(得分:2)
您必须将submit()
调用放在带引号的字符串中。同样适用于msg [i] .id。应引用HTML中的所有值。
output += '<td><input type="button" onclick="submit()" value="' + msg[i].id + '"></td></tr>';
答案 1 :(得分:1)
您正尝试将submit()
分配给按钮onclick
,但实际上在生成字符串output
时调用该函数。它需要在字符串中的引号中,而不是连接在一起。
output += '<td><input type="button" onclick="submit()" value="' + msg[i].id + '"></td></tr>';
//----------------------------------------^^^^^^^^^^^^
更好的策略是完全省略onclick
属性,并使用jQuery的.on()
动态分配方法。通常认为动态绑定事件比将其硬编码为HTML属性更好。
// No onclick attribute in the string:
output += '<td><input type="button" value="' + msg[i].id + '"></td></tr>';
// And a call to .on() in the $(document).ready()
$('input[value="'+msg[i]+'"]').on('click', function() {
submit();
});