点击Mobiscroll日期选择器获取aria-label值问题求助
解决Mobiscroll日期点击时获取aria-label返回null的问题
我在使用Mobiscroll jQuery日期选择器时,想在点击日期时获取其aria-label值并打印到控制台,但每次点击都返回null,代码如下:
HTML代码
<div mbsc-page class="demo-date-picker"> <div style="height:100%"> <div id="demo"></div> </div> </div>
原JS代码
mobiscroll.setOptions({ locale: mobiscroll.localeEn, // Specify language like: locale: mobiscroll.localePl or omit setting to use default theme: 'ios', // Specify theme like: theme: 'ios' or omit setting to use default themeVariant: 'light' // More info about themeVariant: https://docs.mobiscroll.com/5-20-0/calendar#opt-themeVariant }); $(function () { // Mobiscroll Calendar initialization $('#demo').mobiscroll().datepicker({ controls: ['calendar'], // More info about controls: https://docs.mobiscroll.com/5-20-0/calendar#opt-controls display: 'inline' // Specify display mode like: display: 'bottom' or omit setting to use default }); }); var inputs = document.querySelectorAll("[aria-label]"); console.log(inputs.length); for(var i = 0; i < inputs.length; i++){ inputs[i].addEventListener("click", function(e){ console.log(this.getAttribute("aria-label")); }); }
问题原因
- 动态元素绑定时机错误:Mobiscroll的日历元素是在组件初始化后动态生成的,你在代码中直接执行
document.querySelectorAll("[aria-label]")时,这些元素还未被创建,因此获取到的是空集合,事件根本没绑定到目标日期元素上。 - 静态绑定不支持动态元素:即使后续日历元素生成,之前绑定的事件也不会自动作用到新创建的元素上。
解决方案
方案一:事件委托(精准获取aria-label)
利用事件冒泡机制,把点击事件绑定到已存在的父元素(比如#demo)上,不管日历元素什么时候生成,点击都会触发回调,再在回调中判断目标元素是否带有aria-label属性:
mobiscroll.setOptions({ locale: mobiscroll.localeEn, theme: 'ios', themeVariant: 'light' }); $(function () { $('#demo').mobiscroll().datepicker({ controls: ['calendar'], display: 'inline' }); // 通过事件委托绑定点击事件 $('#demo').on('click', '[aria-label]', function() { console.log(this.getAttribute('aria-label')); }); });
方案二:使用Mobiscroll自带的onSelect事件(更符合组件用法)
如果你的核心需求是获取选中的日期,没必要读取aria-label,直接用组件提供的onSelect回调,能更直接拿到选中的日期对象:
mobiscroll.setOptions({ locale: mobiscroll.localeEn, theme: 'ios', themeVariant: 'light' }); $(function () { $('#demo').mobiscroll().datepicker({ controls: ['calendar'], display: 'inline', // 组件自带的选中回调事件 onSelect: function (event, inst) { // 获取选中的日期对象 const selectedDate = event.value; console.log('选中日期对象:', selectedDate); // 若需要aria-label格式的文本,可手动格式化 const ariaLabelText = selectedDate.toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }); console.log('模拟aria-label内容:', ariaLabelText); } }); });
内容的提问来源于stack exchange,提问作者Beldion
相关产品推荐
相关产品推荐

