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」を、初期化時にページに存在する要素に変更します。

以下に例を示します: 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 に答える