jquery how to get the button that has opened the d

2019-02-14 17:10发布

I have a dialog that is opened by many buttons. How can I know which button has opened that dialog?

$('#dialog').dialog({
  autoOpen: false,
  buttons: {
    "Ok": function() { 
      $(this).dialog("close");
    }, 
    "Cancel": function() { 
      $(this).dialog("close");
    } 
  },
  open: function(event, ui) {
    //HERE ::: how to get an HTML OBJECT TO THE ELEMENT THAT OPENED THE DIALOG
  }
});

This is called by:

$('a').live('click',function(){
  $('#dialog').dialog('open');
});

I want to know which <a> tag has called that dialog. Is this possible?

Thanks!

4条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-02-14 17:24

You can assign $(this) to a variable like me and use it later:

$(".locked").on('click',function unlock(){ 
    var me = $(this);

buttons: { 
       "Yes": function() {  
           me.removeAttr('disabled').removeClass('locked');  
       }
查看更多
趁早两清
3楼-- · 2019-02-14 17:25

making the assumption you have a button like such:

<input type="button" class="mybuttons" value="Click Me"/>

and some css like:

.openerclass
{
  background-color: red;
}

add that class when clicked

$(function()
{
    var myevent;
    $(".mybuttons").click(function(event){
       myevent = $(event.target); 
       $(".selector").dialog("open");
    });

    $(".selector" ).dialog({
       open: function(event, ui) { 
       var opener = $(event.target);
       myevent.addClass("openerclass");
       alert(myevent.nodeName);
       ... }
    });
});

Edit: fix syntax error and add another example to make it clear

Edit2: The original was wrong (sort of) in that the opener event is NOT associated with the click event. Modified to use the click event properly.

查看更多
对你真心纯属浪费
4楼-- · 2019-02-14 17:30

In your .live() handler you could store a reference to the element that was clicked on using .data(), like this:

$('a').live('click',function(){
  $('#dialog').data('opener', this).dialog('open');
});

Then to get it later you can grab it from $('#dialog').data('opener'), or $.data(this, 'opener') in the case of the open callback (because this refers to the dialog element). For example your open function may look like this:

open: function(event, ui) {
  $(this).html("Hi, I was opened by: " + $.data(this, 'opener').id);
}

This would show the id property of the anchor you clicked on to open the dialog...you can do whatever you want really, $.data(this, 'opener') refers to the <a /> DOM element.

You can give try a demo of this here

查看更多
\"骚年 ilove
5楼-- · 2019-02-14 17:32

You can give it an id:

$('a').live('click',function(){
      $('#dialogTrigger').removeAttr('id');
      $(this).attr('id', 'dialogTrigger');
      $('#dialog').dialog('open');
}

open: function(event, ui) {
     // do something with $('#dialogTrigger')
}
查看更多
登录 后发表回答