我如何使用jQuery进行调试。 为什么这段代码不起作用?
我正在使用css和jQuery进行弹出式登录表单。
登录弹出窗口是正确的,但我的问题是…关闭弹出窗口的唯一方法是按下提交按钮。 当用户点击然后屏蔽或关闭图像时,为什么它不会关闭。
我对此感到疯狂……
请帮我!!
代码: http : //jsfiddle.net/XZAmn/
HTML:
login
JavaScript的:
$(document).ready(function() { $('a.btn-sign').click(function() { // Getting the variable's value from a link var loginBox = $(this).attr('href'); //Fade in the Popup and add close button $(loginBox).fadeIn(300); //Set the center alignment padding + border var popMargTop = ($(loginBox).height() + 24) / 2; var popMargLeft = ($(loginBox).width() + 24) / 2; $(loginBox).css({ 'margin-top' : -popMargTop, 'margin-left' : -popMargLeft }); // Add the mask to body $('body').append(''); $('#mask').fadeIn(300); return false; }); // When clicking on the button close or the mask layer the popup closed $('a.close, #mask').click( function() { $('#mask, .login-popup').fadeOut(300 , function() { $('#mask').remove(); }); return false; }); });
更改
$('a.close, #mask').click( function() {
至
$(document).on("click", 'a.btn_close, #mask', function () {
使用事件冒泡,以便您可以捕获动态创建的元素上的单击。
其他选项是在创建元素后添加click事件。
您需要绑定的类是.btn_close
$('a.btn_close, #mask').click(function () { $('#mask, .login-popup').fadeOut(300, function () { $('#mask').remove(); }); return false; });
$('a.btn_close, #mask').click(function () { $('#mask, .login-popup').fadeOut(300, function () { $('#mask').remove(); }); return false; });
使用类btn_close而不是关闭你的js修复至少按钮;-)
您尝试在掩码不存在时将close函数绑定到掩码。 你应该在创建掩码之后绑定close函数,我改变了你的JSFiddle,你可以在这里找到它: http : //jsfiddle.net/XZAmn/9/
此外,您没有使用正确的类将关闭函数绑定到关闭按钮。
$(document).ready(function () { $('a.btn-sign').click(function () { // Getting the variable's value from a link var loginBox = $(this).attr('href'); //Fade in the Popup and add close button $(loginBox).fadeIn(300); //Set the center alignment padding + border var popMargTop = ($(loginBox).height() + 24) / 2; var popMargLeft = ($(loginBox).width() + 24) / 2; $(loginBox).css({ 'margin-top': -popMargTop, 'margin-left': -popMargLeft }); // Add the mask to body $('body').append(''); $('#mask').fadeIn(300); $('a.btn_close, #mask').click(function () { $('#mask, .login-popup').fadeOut(300, function () { $('#mask').remove(); }); return false; }); return false; }); // When clicking on the button close or the mask layer the popup closed });
我已经用正确的更改更新了你的小提琴: http : //jsfiddle.net/XZAmn/11/它现在工作正常
基本上你需要改变:
$('a.close, #mask').click(function () {
至:
$(document).on('click', 'a.btn_close, #mask', function () {
你首先得到了错误的类’.close’,然后你将事件绑定到’#mask’,这还不存在,这就是你需要绑定到文档然后使用jQuery’on’过滤元素的原因方法。
$('body').on('click','#mask, .btn_close',function (e) { e.preventDefault(); $('#mask, .login-popup').fadeOut(300, function () { $('#mask').remove(); }); return false; });