我正在使用materializecss Datepicker(https://materializecss.com/pickers.html),这似乎应该很简单,所以我对此有些迷惑。简而言之,我试图仅在单击“确定”按钮时触发事件,但无法在提供的onClose()函数中识别出该事件。如果我尝试监听特定的按钮单击,则会丢失onClose()函数附带的所有内容(该函数很好地打包了该事件所需的所有信息)。
通过onClose()函数,有什么办法可以确定导致onClose()触发的按钮?
在javascript和jquery方面,我是新手,所以非常感谢。
HTML
ForEach-Object
用于初始化日期选择器的JavaScript代码
<input type="text" class="datepicker" value="8/4/2018" job="533">
Datepicker模式已创建
$(document).ready(function(){
$('.datepicker').datepicker({
"format": "m/d/yyyy",
onClose() {
// only do something if this was fired from the "Done" button
}
})
});
答案 0 :(得分:0)
下面的代码可以帮助您获得所需的按钮。将2个侦听器添加到onOpen()中打开的模态的完成按钮和取消按钮,并删除侦听器onClose()。 这将为您工作。
<script>
$(document).ready(function() {
function Cancel() {
if(!this.hasEvent) {
this.hasEvent = true;
console.log('Clicked on cancel btn:', this.cancelBtn);
}
}
function Done() {
if(!this.hasEvent) {
this.hasEvent = true;
console.log('Clicked on done btn:', this.doneBtn);
}
}
$('.datepicker').datepicker({
"format": "m/d/yyyy",
onOpen: function(e) {
var that = this;
that.hasEvent = false;
this.cancelBtn.addEventListener('click', Cancel.bind(that))
this.doneBtn.addEventListener('click', Done.bind(that))
},
onClose: function(e) {
var that = this;
this.cancelBtn.removeEventListener('click', Cancel.bind(that))
this.doneBtn.removeEventListener('click', Done.bind(that))
}
})
});
</script>
答案 1 :(得分:0)
首先,您可以仅使用Datepicker
来初始化vanillaJS
,然后如果您检查materialize.css
文件,则会发现“确定”按钮的class name
,即, .datepicker-done
。您可以将addEventListener附加到此按钮,然后调用所需的任何函数。
document.addEventListener('DOMContentLoaded', function () {
var elems = document.querySelector('.datepicker');
var instance = M.Datepicker.init(elems);
var doneBtn = document.querySelector('.datepicker-done');
doneBtn.addEventListener('click', callThis); //Attaching a 'click' event to done button
function callThis() {
console.log('Done Button clicked only!'); //Checking the done button click
console.log(elems.getAttribute('job')); //To get the job attribute value
}
});
答案 2 :(得分:0)
所有答复都对解决这一问题非常有帮助,谢谢那些贡献者!
我不知道这是否是最优雅的解决方案,但是它对我有用。我保留了jquery调用以初始化页面上的所有日期选择器,然后使用forEach
循环添加了事件侦听器。为了获得我想要的值,我不得不进行一系列疯狂的.parent()
调用,但这始终为我提供了正确的信息。希望这可以帮助将来有人处理同一问题(或者可以帮助其他人提供更有效的答案!)。
$(document).ready(function(){
$('.datepicker').datepicker({
"format": "m/d/yyyy",
})
});
document.addEventListener('DOMContentLoaded', function () {
var doneBtn = document.querySelectorAll('.datepicker-done');
doneBtn.forEach(function(elem) {
elem.addEventListener('click', callThis)
});
});
function callThis() {
var update = $(this).parent().parent().parent().parent().parent().siblings('input');
// do the thing I want with that input value
};