在jquery插件中委托父亲事件

时间:2015-07-29 10:09:03

标签: jquery jquery-plugins

在我的插件中,我动态创建项目并将事件委托给这些项目。 我的问题是委托我的对象外面(父)的事件"这个"喜欢标题所以 你可以在同一页面上的多个表上使用该插件。

;(function ($, window, document, undefined) {
    'use strict';

    $.fn.myPlugin = function(options) {

        return this.each(function() {
            //var $this = $(this);
            //var that = this;

            /* RENDER DYNAMICALLY "THIS" HEADER */
            var hd = "<div class=\"header\"><button type=\"button\" id=\"clickMe\">Click Me</button></div>";
            $(hd).insertBefore(this);

            /* RENDER DYNAMICALLY "THIS" TD */
            var rows = "<tr><td>1</td><td>200</td><td>Foo</td></tr>";
            $(this).find('tbody').html(rows);

            /* DELEGATE "THIS" TD ELEMENT*/
            $(this).on('click', 'td', function() {
                //do something
            });

            /* DELEGATE PARENTS "THIS" ELEMENT */
            // problem if using plugin for more tables in the same page,
            // because header might belong to multiple tables
            $('.header').on('click', '#clickMe', function(e) {
                e.stopPropagation();
                //do something
            });

        });
    };

})(jQuery, window, document);


$(#tbl).myPlugin();

HTML

<table id="tbl" class="table">
    <thead>
        <tr>
            <th>ID</th>
            <th>Code</th>
            <th>Name</th>
        </tr>
    </thead>
    <tbody></tbody>
</table>

如何仅委派属于我或此对象父母的事件? 谢谢

1 个答案:

答案 0 :(得分:1)

如果我理解你的麻烦,这可能会有所帮助:

&#13;
&#13;
class Test {
    private $date;
    public getDate() { return $this->date; }
    public setDate($date) {
        // here some modification value or something else
        $this->date = $date;
    }
}
&#13;
;(function ($, window, document, undefined) {
    'use strict';

    $.fn.myPlugin = function(options) {

        return this.each(function() {
            //var $this = $(this);
            var that = this;

            /* RENDER DYNAMICALLY "THIS" HEADER */
            var hd = "<div class=\"header\"><button type=\"button\" id=\"clickMe\">Click Me</div>";
            $(hd).insertBefore(this);

            /* RENDER DYNAMICALLY "THIS" TD */
            var rows = "<tr><td>1</td><td>200</td><td>Foo</td></tr>";
            $(this).find('tbody').html(rows);

            /* DELEGATE "THIS" TD ELEMENT*/
            $(this).on('click', 'td', function() {
                //do something
//                alert($(this).closest('table').attr('id')); 
            });

            /* DELEGATE PARENTS "THIS" ELEMENT */
          // no problem more: you are added button BEFORE table, so get the prev element with class .header
            $(this).prev('.header').on('click', '#clickMe', function(e) {
                e.stopPropagation();
                alert('clicked button for ' + $(that).attr('id') + ' table.'); //get table in button
            });

        });
    };

})(jQuery, window, document);


$('.table').myPlugin();
&#13;
&#13;
&#13;