我正在尝试创建事件监听器并将其添加到jquery中的按钮。我能够做到这一点,但我的问题是,当我点击表单中的任何一个按钮时,此事件就会触发。
这是我的代码:
$('#submitPh').on('click',function(e){
e.preventDefault();
secCheck($(this).attr('id'));
});
function secCheck(invoker) {
console.log('called');
var id = 'secModal', title = '<h3>Security Verification</h3>',
body = $('<form/>').attr({'method': 'post', 'action': '', 'id': 'secCheck'}).append($('<div/>').addClass('form-group')
.append($('<div/>').addClass('controls')
.append($('<label/>').attr({'for': 'verPass'}).addClass('control-label').text('Please enter your password'), $('<input/>').attr({'type': 'password', 'id': 'verPass', 'name': 'verPass', 'value': '', 'placeholder': 'Enter your password'})
.addClass('form-control'))), $('<div/>').addClass('form-group').append($('<div/>').addClass('col-lg-10 warning-mes')),$('<div/>').addClass('form-group').append($('<button/>').click(confCheck()).attr({'type': 'button', 'id': 'secCheckSubmit'}).addClass('btn btn-default').text('Submit')));
createModal(id, title, body, invoker);
}
function createModal(id, title, body, invoker) {
var modal = $('<div/>').attr('id', id).addClass('modal fade')
.append($('<div/>').addClass('modal-dialog')
.append($('<div/>').addClass('modal-content')
.append($('<div/>').addClass('modal-header')
.append($('<button/>').attr({'data-dismiss': 'modal', 'area-hidden': true}).addClass('close').html('×'), title), $('<div/>').addClass('modal-body').html(body), $('<div/>').addClass('modal-footer')
.append($('<button/>').attr({'type': 'button', 'data-dismiss': 'modal'}).addClass('btn btn-default').text('Close')))));
if (!$('div#' + id).length) {
$('body').append(modal);
}
showModal('#' + id, invoker);
}
function showModal(sId, invoker) {
var $this = invoker;
var id = sId;
var $target = $(sId || (id && id.replace(/.*(?=#[^\s]+$)/, ''))); //strip for ie7
var option = $target.data('modal') ? 'toggle' : $.extend({remote: !/#/.test(id) && id}, $target.data());
this.modal = $target
.modal(option, this)
.one('hide', function() {
$this.is(':visible') && $this.focus();
});
}
function confCheck() {
alert();
}
这就是我的方式。但是,如上所述,这并没有产生预期的结果。
请有人帮我解决这个问题......
修改
答案 0 :(得分:1)
答案 1 :(得分:1)
应该是
$('<button/>').click(confCheck)
您需要将函数引用作为参数传递给click()
,不要将其调用并发送结果
答案 2 :(得分:0)
更好的是,您应该为新创建的按钮提供类名,并为事件监听提供详细信息
$('#button').append($('<button/>', { class: "test" }));
$("body").on("click", ".test", function () { });