Get the element triggering an onclick event in jquery?

后端 未结 4 604
暗喜
暗喜 2020-12-08 09:15

I have a form where i\'ve replaced the submit button with an input (with type=button) with an onclick which calls an existing function:

相关标签:
4条回答
  • 2020-12-08 09:48

    You can pass the inline handler the this keyword, obtaining the element which fired the event.

    like,

    onclick="confirmSubmit(this);"
    
    0 讨论(0)
  • 2020-12-08 09:48

    It's top google stackoverflow question, but all answers are not jQuery related!

    $(".someclass").click(
        function(event)
        {
            console.log(event, this);
        }
    );
    

    'event' contains 2 important values:

    event.currentTarget - element to which event is triggered ('.someclass' element)

    event.target - element clicked (in case when inside '.someclass' [div] are other elements and you clicked on of them)

    this - is set to triggered element ('.someclass'), but it's JavaScript element, not jQuery element, so if you want to use some jQuery function on it, you must first change it to jQuery element: $(this)

    When your refresh the page and reload the scripts again; this method not work. You have to use jquery "unbind" method.

    0 讨论(0)
  • 2020-12-08 09:49

    If you don't want to pass the clicked on element to the function through a parameter, then you need to access the event object that is happening, and get the target from that object. This is most easily done if you bind the click event like this:

    $('#sendButton').click(function(e){
        var SendButton = $(e.target);
        var TheForm = SendButton.parents('form');
        TheForm.submit();
    
        return false;
    });
    
    0 讨论(0)
  • 2020-12-08 10:00

    Try this

    <input onclick="confirmSubmit(event);" type="button" value="Send" />
    

    Along with this

    function confirmSubmit(event){
                var domElement =$(event.target);
                console.log(domElement.attr('type'));
            }
    

    I tried it in firefox, it prints the 'type' attribute of dom Element clicked. I guess you can then get the form via the parents() methods using this object.

    0 讨论(0)
提交回复
热议问题