1

メソッドui .buttonで委任を使用して割り当てるための正しい構文は何ですか?.on

私はこの種の構造を成功させずに試しました:

$("body").on("load","a.button",function(){ $("a.button").button(); });

口頭で:ページが読み込まれた後、ui.buttonメソッドを使用して各.buttonクラス要素をグラフィックモードに切り替えます。動的にロードされたコンテンツを含みます。

4

2 に答える 2

4

委任する場合、ハンドラーは親要素()のイベントにバインドされます。このイベントは、bodyトリガー時に、セレクター(a.button)に一致する要素を検索します。

これが、DOMの挿入/変更のイベントがないために例が機能しない理由です(loadイベントはそのようには機能しません)。.button()挿入後、要素を自分でトリガーする必要があります。

派手になり、カスタムイベントを使用して動的に挿入されたコンテンツの更新を処理する場合は、次のようにすることができます。

HTML

<div id="container"></div>

JavaScript

// Custom event listener to update the content on demand
var container = $("#container").on("update", function() {
    // Turn any a.button elements into jQuery UI buttons
    $("a.button", container).button();
});

// Get some content
$.get("/foo", function(html) {
    // Insert content to container and trigger an update
    container.html(html).trigger("update");
});

注意:より明確なデモンストレーションのために、コンテナ要素を追加しました。これはそれがなくても機能し、必要に応じて直接機能しdocument.bodyます。

updateロード時にカスタムイベントをトリガーする場合はcontainer.trigger("update")、ドキュメントに追加するだけです。

于 2012-09-12T22:03:16.260 に答える
0

お役に立てれば:

$(function() {
    $( "input:submit, a, button", ".demo" ).button();

    // Original example method
//    $( "a", ".demo" ).click(function() { return false; });

    // on(), if you're not loading the targets after page-load
//    $( "a", ".demo" ).on ("click", function() { return false; });

    // on(), if you are loading the targets after page-load
    $( document ).on ("click", "a, .demo", function() { return false; });
});​

ここでのデモ:http://jsfiddle.net/FG6rd/

于 2012-09-12T22:11:36.007 に答える