我正在开发一个JavaScript聊天机器人库。某些命令会更改可用按钮(例如,当您启动“测试命令”时,这些选项可用:是,否,和取消)
当您点击取消时,它会像我预期的那样放回原始按钮,但它们不可点击?如何让它们再次点击?
var commands = [
"test command",
"clear messages"
];
function message(status, message) {
if (status == "sent") {
$(".messages").append("<div class='message sent'><p>" + message + "</p></div>");
} else {
$(".messages").append("<div class='message from'><p>" + message + "</p></div > ");
}
$(".messages").animate({
scrollTop: $('.messages').prop("scrollHeight")
}, 500);
}
function buttons(commands) {
$(".buttons").html("");
$.each(commands, function(index, value) {
var id = value.split(" ").join("-");
$(".buttons").append('<div class="button" id ="command_' + id + '">' + value + '</div>');
});
}
buttons(commands);
$("#command_test-command").click(function() {
message("sent", "test command");
var parameters = [
"yes",
"no",
"cancel"
];
buttons(parameters);
$("#command_yes").click(function() {
message("sent", "yes");
message("from", "you said yes");
});
$("#command_no").click(function() {
message("sent", "no");
message("from", "you said no");
});
$("#command_cancel").click(function() {
message("sent", "cancel");
message("from", "you said cancel");
buttons(commands);
});
});
$("#command_clear-messages").click(function() {
$(".messages").html("");
});
答案 0 :(得分:1)
我不建议使用js设置html,但这应该触发点击
$(".buttons").on('click','#command_test-command',function() {
// test-command
});
$(".buttons").on('click','#command_clear-messages',function() {
// clear messages
});
为您的例子
var commands = [
"test command",
"clear messages"
];
function message(status, message) {
if (status == "sent") {
$(".messages").append("<div class='message sent'><p>" + message + "</p></div>");
} else {
$(".messages").append("<div class='message from'><p>" + message + "</p></div > ");
}
$(".messages").animate({
scrollTop: $('.messages').prop("scrollHeight")
}, 500);
}
function buttons(commands) {
$(".buttons").html("");
$.each(commands, function(index, value) {
var id = value.split(" ").join("-");
$(".buttons").append('<div class="button" id ="command_' + id + '">' + value + '</div>');
});
}
$(".buttons").on('click','#command_test-command',function() {
message("sent", "test command");
var parameters = [
"yes",
"no",
"cancel"
];
buttons(parameters);
}).on('click','#command_clear-messages',function() {
$(".messages").html("");
}).on('click','#command_yes',function() {
message("sent", "yes");
message("from", "you said yes");
}).on('click','#command_no',function() {
message("sent", "no");
message("from", "you said no");
}).on('click','#command_cancel',function() {
message("sent", "cancel");
message("from", "you said cancel");
buttons(commands);
});
buttons(commands);