javascript - 使用 mouseup 事件触发表行中的按钮单击事件

标签 javascript jquery fullcalendar

我正在使用 jQuery fullCalendar 插件。

我在日历的 select 属性后面有一个事件:

 $("#calendar").fullCalendar({
       select: function(start,end,jsEvent,view){
                  doSomething();
               }
 });

select 属性背后的事件是日历的全天单元格的 mouseup 事件。

我试图在日历的日期单元格内放置一个按钮,但无法触发该按钮的单击事件。

我已经阅读了 stackoverflow 中关于冒泡的各种提交内容,但这些解决方案都不起作用:

  $("#testbutton").click(function(e){
        e.stopPropagation();
        doSomethingElse();
  });

即使我从 fullcalendar 和所有关联代码中删除 select 属性(这会导致日期单元格突出显示,但不会触发任何事件),按钮的单击事件仍然不会触发。

有什么想法吗?

最佳答案

因为按钮是动态添加的,所以您当前的 jQuery 注册将不会绑定(bind)。如果您使用“on”事件绑定(bind),它将适用于动态元素。尝试如下操作:

//Replace ".dynamic-button-class" with a target that points to your button.
$(document).on("click", ".dynamic-button-class", function(e) {
    e.preventDefault();
    doSomething();
});

“on”语法绑定(bind)到所有 future 匹配该模式的 DOM 元素以及渲染时出现的元素。

请参见此处:http://api.jquery.com/on/

这里:Event binding on dynamically created elements?

您还需要避免重复的事件注册。通过将一个事件绑定(bind)到另一个事件中,每次触发父事件时都会重新绑定(bind)该事件,这可能不是您想要的。

相反,请考虑这样的解决方案:

//This method is registered once for all buttons with a "dynamic-button" class attribute and is triggered for each one clicked.
$(document).on("click", ".dynamic-button", function(e) {
    //Load the values stored in the hidden fields.
    var formStartDate = $(e.currentTarget).closest("input[name='StartDate']").val();
    //etc...
    $(document).trigger("calendar-button-clicked", {StartDate: formStartDate}); // Pass the form arguments as a JavaScript object to the calendar-button-clicked event hander
});

$(document).bind("calendar-button-clicked", function(e, data) {
    //Do something with the values in data.
});

//Single event triggered when a calendar selection is made
$(document).bind("add-button", function(e, data) {
    //Code that adds your button to the page here but also checks to see if the button has already been added.
    //persist the values from Data into some kind of form hidden form fields.
    console.log(data.StartDate);
});

$("#calendar").fullCalendar({
    select: function(start, end, jsEvent, view){
        $(document).trigger("add-button", {StartDate: start, EndDate: end, SourceEvent: jsEvent, View: view});
    }
});

编辑:这是我设置的一个快速 fiddle ,它可以工作并演示这个概念。

http://jsfiddle.net/xDaevax/5282Q/

关于javascript - 使用 mouseup 事件触发表行中的按钮单击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24997058/

相关文章:

javascript - ajax请求成功后在jstree中追加子节点的问题

javascript - 通过几个选定的选项访问多个选择上的特定属性

javascript - 全日历在当前月份的月 View 中的错误日期显示事件

javascript - FullCalendar - 跨越一整天的事件一天太短了

javascript - 向 JavaScript 添加附加变量

javascript - AJAX 请求完成后,如何调用 PartialView 中定义的 JavaScript 函数?

javascript - Bootstrap Modal-Manager 禁用溢出

jquery - 全日历 4 天 View

javascript - knockout js : data-bind click not working

jquery - 无法使用 Ajax 和 jQuery Validate 提交表单