JQuery click事件附加到多个元素

时间:2016-11-28 16:17:05

标签: javascript jquery jquery-ui

我有一个在对话框标题中创建按钮元素的函数。但是,click事件会附加到所有按钮而不是当前按钮。

_createTitlebarButtons : function(){
    for (var each in this.options.titlebarButtons ) {
        var self = this,
            props = this.options.titlebarButtons[each];


        if ( !props.icon ){ props.icon = ""}
        if ( !props.name ){ props.name = "button-"+each.toString()}
        if ( !props.click ){ props.click = function(){} }
        if ( !props.text ){ props.text = "" }

        var curButton = $( "<button type='button' id='btn-"+each+"' ></button>" ).button({
                type: "button",
                label: $( "<a>" ).text( props.text ).html(),
                icon: props.icon,
                showLabel: false
            })
            .attr("name", props.name)
            .css("right", 3+22*(Number(each)+1))
            .appendTo( this.uiDialogTitlebar )
            .on( "click", function( event ) {
                        event.preventDefault();
                        props.click.apply( self.element[ 0 ], arguments );
                    });

        this._addClass( curButton, "ui-dialog-titlebar-close" );
    }
},

所有图标和类都有效。但是,click事件会附加到所有按钮而不是一个按钮。因此,如果我有多个按钮,则所有按钮的点击事件都是相同的。它将成为最后一个按钮的click事件。所以:

titlebarButtons : [
        {   
            name: "button1",
            text: "tooltip",
            icon: "ui-icon-heart",
            click:function(){
                console.log("Button1 Clicked");
                console.log(this);
            }
        },
        {   
            name: "button2",
            text: "tooltip",
            icon: "ui-icon-close",
            click:function(){
                console.log("Button2 Clicked");
                console.log(this);
            }
        }
    ]

将创建2个按钮,但点击它们都会说“Button2 Clicked”,而第一个应该说“Button1 clicked”。

编辑:由于范围问题,不得不使用$ .each而不是for循环。

$.each( this.options.titlebarButtons, function(index){
        console.log(this);

        var props = this;

        if ( !props.icon ){ props.icon = ""}
        if ( !props.name ){ props.name = "button-"+index}
        if ( !props.click ){ props.click = function(){} }
        if ( !props.text ){ props.text = "" }

        var curButton = $( "<button type='button' ></button>" ).button({
                type: "button",
                label: $( "<a>" ).text( props.text ).html(),
                icon: props.icon,
                showLabel: false
            })
            .attr("name", props.name)
            .css("right", 3+22*(Number(index)+1))
            .appendTo( self.uiDialogTitlebar )
            .on( "click", function( event ) {
                        event.preventDefault();
                        props.click.apply( self.element[ 0 ], arguments );
                    });


        self._addClass( curButton, "ui-dialog-titlebar-close" );
    } ) 

2 个答案:

答案 0 :(得分:1)

创建了以下示例:https://jsfiddle.net/Twisty/ookwg8bq/

<强>的jQuery

$(function() {
  var uiDialog = {
    options: {
      titlebarButtons: [{
        name: "button1",
        text: "tooltip",
        icon: "ui-icon-heart",
        click: function() {
          console.log("Button1 Clicked");
          console.log(this);
        }
      }, {
        name: "button2",
        text: "tooltip",
        icon: "ui-icon-close",
        click: function() {
          console.log("Button2 Clicked");
          console.log(this);
        }
      }]
    },
    uiDialogTitlebar: "#uiDialogTitlebar",
    _createTitlebarButtons: function() {
      var self = this;
      $.each(self.options.titlebarButtons, function(ind, elem) {
        var props = self.options.titlebarButtons[ind];

        if (!props.icon) {
          props.icon = ""
        }
        if (!props.name) {
          props.name = "button-" + ind
        }
        if (!props.click) {
          props.click = function() {}
        }
        if (!props.text) {
          props.text = ""
        }

        var curButton = $("<button>", {
            type: 'button',
            id: 'btn-' + ind,
            name: props.name,
            class: "ui-dialog-titlebar-close"
          }).button({
            type: "button",
            label: props.text,
            icon: props.icon,
            showLabel: false
          })
          .css("right", 3 + 22 * (ind + 1))
          .appendTo(self.uiDialogTitlebar)
          .click(function(event) {
            event.preventDefault();
            props.click.apply(elem, []);
          });
      });
    }
  };

  uiDialog._createTitlebarButtons();

});

这会创建两个按钮,您可以单击每个按钮。由于right样式,它们有些重叠。我在FireFox w / FireBug控制台中得到以下结果:

Button1 Clicked
/_display/ (line 73)
Object { name="button1",  text="tooltip",  icon="ui-icon-heart",  more...}
/_display/ (line 74)
Button2 Clicked
/_display/ (line 81)
Object { name="button2",  text="tooltip",  icon="ui-icon-close",  more...}

答案 1 :(得分:0)

// trigger event when click on a button
$('button').on('click', function() {
    _createTitlebarButtons($(this));
};

// function called by the event
function _createTitlebarButtons(button) {
    // List all the actions that affect only the button you want to refer to it as "button". i.e:
    button._addClass( curButton, "ui-dialog-titlebar-close" );
};