0

我在我的页面上使用 jQuery 日历和输入掩码插件,它们工作正常。我有一个添加按钮,它添加一行带有文本框,但插件不适用于新添加的行。我怎样才能解决这个问题?如果在添加按钮单击事件中再次调用插件代码,它们似乎可以工作,但我想知道是否有更好的方法让它工作。谢谢。

$(".add-row").on("click", function () {
    // Add row   
    // Call AGAIN to make it work
    $(".time").mask("99:99");
    $(".date").datepicker();
});

$(".time").mask("99:99");

$(".date").datepicker();
4

2 回答 2

0

您需要将 on() 绑定到页面上存在的元素,以便从该元素触发单击事件侦听器。

尝试这样的事情:

$(".some-other-element").on("click", ".add-row", function(event){
    // Add row   
    // Call AGAIN to make it work
    $(".time").mask("99:99");
    $(".date").datepicker();
});

将“some-other-element”更改为 init 页面上存在的元素。

这是一个例子:http: //jsfiddle.net/TheFiddler/bv27J/

看看“委托事件”的 API:http: //api.jquery.com/on/

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). 

To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. 

If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next.

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.
于 2013-03-28T17:53:28.770 回答
-1

您必须再次调用它们,但仅限于您正在创建的元素。就像是:

$(".add-row").on("click", function () { 
    var scheduleDate = '<input type="text" name="txtScheduleDate" class="date" />'; 
    var row = $("<div><div class='div-table-col'>" + scheduleDate + "</div><div>").addClass("div-table-row"); 
    $(this).closest('h3').next('div').append(row); 

    row.find('input[name=txtScheduleDate]').datepicker();

    return false; 
}); 

演示:http: //jsfiddle.net/Uat4R/

于 2013-03-28T17:49:12.323 回答