开发者

How to know which button is clicked

开发者 https://www.devze.com 2023-03-03 16:58 出处:网络
In my page I have many edit buttons each name starts with \"edit\" and then some id. I want to know any of my edit buttons is clicked or not.

In my page I have many edit buttons each name starts with "edit" and then some id. I want to know any of my edit buttons is clicked or not. In details, I have form. In form I have many edit buttons which name starts with "edit" , delete buttons which name starts with "delete" and 1 add button. All are submit buttons. form onsubmit I call JavaScript function in which I want if the 开发者_运维百科button is edit confirm("some text") else submit form. How can I do that in JavaScript? I think give all these buttons same id and then getElementById but then how con I change?


This is simple using jQuery:

$(':button').click(function() {
  // reference clicked button via: $(this)
  var buttonElementId = $(this).attr('id');
});

Try it out: http://jsfiddle.net/7YEay/

UPDATE based on feedback in comments

This is untested/pseudo code:

$(':submit').click(function(event) {
  var buttonName = $(this).attr('name');

  if (buttonName.indexOf('edit') >= 0) {
    //confirm("some text") logic...
  }

  event.preventDefault();
});

This documentation may be helpful too: http://api.jquery.com/submit/


function MyOnSubmit(e){
   e = e || window.event;
   // srcElement for IE, target for w3c
   var target = e.target || e.srcElement;
   if (target.id.indexOf("edit") > -1){
     // an edit button fired the submit event
   }
}

although i advice you research further to find a better way to handle edit and delete buttons (like making them links with href=editpage.jsp?id=23)


I'm pretty sure you just answered this yourself...

Each starts with "edit", and ends with a unique ID? So... $(button).attr("id") would give you that. Store it in a variable? Not sure what you're trying to do..


bind click event on all button:

for (var i = 0; i < buttons.length; i++) {
    var button = buttons[i];
    if (button.addEventListener) {
        button.addEventListener('click', handler, false);
    }
    else {
        button.attachEvent('onclick', handler);
    }
}

in your event handler, get the Event object, and then get the target:

function handler(e) {
    e = e || window.event;
    // srcElement for IE, target for w3c
    var target = e.target || e.srcElement;
    var id = target.name.substring(4);
    /* your code rely on id */
}


I think you might not have phrased your question correctly. If you are using jquery, locating the button is as easy as $('#id'), and if you want to store any information on that button, you can either add an attribute or use jquery.data function.

$('#id').attr("pressed", "true");

Or

$('#id').data('pressed', 'true');
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号