2017-03-08 12 views
1

我想追加jQuery UI的,日期选择器,我不能让事件处理工作:通过多条链路jQuery的事件处理程序将无法正常工作

$('.ui-datepicker').on('click', 'a.ui-datepicker-next', 'a.ui-datepicker-prev', function(event) { 
    event.preventDefault(); 
     console.log("CLICK"); 
}); 

我没有什么记录到控制台,当我点击链接。这里是html:

<div id="ui-datepicker-div" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"...> 
    <div class="ui-datepicker-header ui-widget-header ui-helper-clearfix- ui-corner-all"> 
     <a class="ui-datepicker-next ui-corner-all"...></a> 
     <a class="ui-datepicker-prev ui-corner-all"...></a> 
     ... 

什么我需要把事件处理程序作为触发器? jQuery位于我的html页脚的<script>jQuery here</script>中。

编辑:链接是不正确的 - a.ui-datepicker-montha.ui-datepicker-year变更为a.ui-datepicker-nexta.ui-datepicker-prev

感谢

回答

2

你的语法是不完全正确。选择器需要以逗号分隔,但使用相同的字符串。试试这个:

$('.ui-datepicker').on('click', 'a.ui-datepicker-month, a.ui-datepicker-year', function(e) { 
    e.preventDefault(); 
    console.log("CLICK"); 
}); 

说明:'a.ui-datepicker-month, a.ui-datepicker-year'。还请注意,使用e而不是event,因为这将覆盖某些浏览器具有的全局事件对象。

*问题编辑后更新:

还有两个问题。首先正确的类别是a.ui-datepicker-preva.ui-datepicker-next。此外,DOM的加载中不存在ui.-datepicker元素,因此没有任何事件可以绑定到该事件。要解决这个问题,你可以使用$(document),尽管理想情况下你应该使用最接近的父元素给那些你想要加载的DOM中的那些元素。试试这个:

$(document).on('click', 'a.ui-datepicker-prev, a.ui-datepicker-next', function(e) { 
    e.preventDefault(); 
    console.log("CLICK"); 
}); 

Working example

+0

更正语法。仍然没有登录到控制台,虽然.... @Rory McCrossan –

+0

你的代码没有什么特别的错误。这个问题必须与事件的附加方式有关。执行上面的代码时,'.ui-datepicker'元素是否存在?作为一个测试,尝试用'$(document)'替换'$('。ui-datepicker')' –

相关问题