简体   繁体   English

jQuery click事件附加到多个元素

[英]JQuery click event attaches to more than one element

I have a function that creates button elements in dialog header. 我有一个在对话框标题中创建按钮元素的函数。 However, the click event gets attached to all the buttons instead of current button. 但是,单击事件将附加到所有按钮而不是当前按钮。

_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" );
    }
},

All the icons and classes work. 所有图标和类均有效。 However, the click event gets attached to all the buttons instead of one button. 但是,单击事件将附加到所有按钮,而不是一个按钮。 So if I have multiple buttons the click event is going to be the same for all buttons. 因此,如果我有多个按钮,则所有按钮的点击事件都将相同。 And its going to be the click event of the last button. 这将是最后一个按钮的click事件。 So: 所以:

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);
            }
        }
    ]

Will create 2 buttons but on click they both will be saying "Button2 Clicked" whereas the first one should say "Button1 clicked". 将创建2个按钮,但是在单击时它们都将显示“ Button2 Clicked”,而第一个应该显示“ Button1 clicked”。

EDIT: Had to use $.each instead of for loop because of scope problems. 编辑:由于范围问题,不得不使用$ .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" );
    } ) 

Created the following example: https://jsfiddle.net/Twisty/ookwg8bq/ 创建了以下示例: https : //jsfiddle.net/Twisty/ookwg8bq/

jQuery 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();

});

This creates both buttons and you can click on each button. 这将创建两个按钮,您可以单击每个按钮。 They sort of overlap due to the right styling. 由于样式right它们有点重叠。 I get the following results in FireFox w/FireBug console: 我在带有FireBug控制台的FireFox中得到以下结果:

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...}
// 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" );
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM