我正在尝试创建一个 timepicker popup form 里面。我正在努力处理事件委托(delegate) - 我能够让时间选择器在表单之外工作,但不能在表单内部工作。
我当前的代码,没有时间选择器弹出窗口:
$(document).ready(function() {
$('#timepick').timepicker({
showPeriod: true,
showLeadingZero: true
});
});
$(function() {
$( "#dialog-form" ).dialog({
autoOpen: false,
height: 300,
width: 350,
modal: true,
buttons: {
"Add Time": function() {
$( "#time-table tbody" ).append( "<tr>" +
"<td>" + time.value + "</td>" +
"</tr>" );
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
},
});
$("#add-time").button().click(function() {
$( "#dialog-form" ).dialog( "open" );
});
});
这在弹出框内部不起作用,仅适用于弹出框外部的#timepick。我知道我需要以某种方式利用 .on() jquery 函数。
$(document).ready(function() {
$('#timepick').on("click", function(){
timepicker({
showPeriod: true,
showLeadingZero: true
});
});
也没有用。
当前试用的粘贴箱:
编辑:
所以这最有效:
$(document).ready(function() {
$('#dialog-form').on('click','#time',function() {
$('#time').timepicker({
showPeriod: true,
showLeadingZero: true
});
});
});
唯一的问题是,它目前需要您单击该框,然后添加事件处理程序,然后单击关闭并单击返回 - 因此在工作之前需要单击一次。如何让它立即点火?以某种方式使用 .trigger()?
最佳答案
您没有委托(delegate)任何事情。您只需将事件直接绑定(bind)到 timepick 元素上即可。
如果您想委托(delegate)事件,则需要一个额外的选择器:
$('body').on('click','.allElementsYouNeedSelector',function(){});
上面的代码将应用匿名回调函数作为在具有 allElementsYouNeedSelector
的任何元素上触发的所有点击事件的事件处理程序> 类,$('body')
标记中任何地方。
因此,如果您想委托(delegate),请说出您的 dialog-form
元素:
$('#dialog-form').on('click','*',function()
{//will be called when any child of the #dialog-form is clicked
});
请注意,如果您使用这样的 on
方法,它会被转换为 the delegate
method内部。
更新:
根据您的更新,我必须说:为具有唯一 ID 的元素委托(delegate)事件根本没有意义。也许你可以试试这个:
$('#time').on('click',{showPeriod: true,showLeadingZero: true},timepicker);
这会将点击监听器绑定(bind)到 #time
元素,并将 timepicker
方法应用为事件处理程序,传递对象文字 {showPeriod: true,showLeadingZero: true}
作为参数,就像您所做的那样。当然,您可以使用委托(delegate)来做同样的事情:
$('#dialog-form').on('click','*',function()
{//regardles of which child was clicked, apply the timepicker method to #time
$.timepicker.apply($('#time'),[{showPeriod: true,showLeadingZero: true}]);
});
与以往一样,为了避免在每次调用时扫描 DOM,您可以添加一个闭包
$('#dialog-form').on('click','*',(function(time)
{
return function()
{
time = time || $('#time');//in case $('#time') didn't exist when function was created
$.timepicker.apply(time,[{showPeriod: true,showLeadingZero: true}]);
};
}($('#time')));
关于Javascript 事件委托(delegate)——向弹出表单添加时间选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13619656/