javascript - How can I get the function bound to an onclick attribute? - Stack Overflow

I've got a function bound to the onclick event in the html, like so:<script>function f1(){ a

I've got a function bound to the onclick event in the html, like so:

<script>
    function f1(){ alert('hello world'); };
</script>

<a onclick="f1()">test</a>

I'd like to do something with that function, like bind it to another event. I tried this in jQuery:

var defaultFunction = $('a').attr('onclick');

but defaultFunction is defined as a string rather than the function itself. I can evaluate it with eval(defaultFunction), but that makes me feel dirty. Is there a way I can access the function itself, rather than the string?

i.e. I'd like to be able to call defaultFunction() and do whatever the default onclick behavior bound to the a element is. (In this case, call f1()).

Here's a fiddle that tries to do that, but fails.

I've got a function bound to the onclick event in the html, like so:

<script>
    function f1(){ alert('hello world'); };
</script>

<a onclick="f1()">test</a>

I'd like to do something with that function, like bind it to another event. I tried this in jQuery:

var defaultFunction = $('a').attr('onclick');

but defaultFunction is defined as a string rather than the function itself. I can evaluate it with eval(defaultFunction), but that makes me feel dirty. Is there a way I can access the function itself, rather than the string?

i.e. I'd like to be able to call defaultFunction() and do whatever the default onclick behavior bound to the a element is. (In this case, call f1()).

Here's a fiddle that tries to do that, but fails.

Share Improve this question asked Aug 27, 2014 at 16:16 ckerschckersch 7,6972 gold badges41 silver badges48 bronze badges 5
  • I think the real question is, why are you doing this, and what are you really trying to achieve? :) – xec Commented Aug 27, 2014 at 16:30
  • 1 Mostly I'm trying to satisfy my own curiosity. I was answering a different question and wasn't sure how to go about getting the function bound to an onclick attribute, so I figured I'd ask. – ckersch Commented Aug 27, 2014 at 16:34
  • You may want to review the other answers as the one you have currently selected is not the correct answer. – Patrick W. McMahon Commented Aug 29, 2014 at 21:52
  • 1 It's the only one that actually answers my question. The rest tell me how I should be binding functions differently. – ckersch Commented Sep 2, 2014 at 14:21
  • onclick() in html will soon no longer work and is considered bad. Your code will break as browsers update. binding is the way it will be for now on. – Patrick W. McMahon Commented Sep 29, 2014 at 21:50
Add a ment  | 

6 Answers 6

Reset to default 2

see this document.getElementById("id_of_your_element").onclick if that help you, it will return click handler, and you can call that, but its not right to raise events manually

Something like this:

Example

var defaultFunction = $('a').attr('onclick');
var defaultFunctionName = defaultFunction.substring(0, defaultFunction.indexOf('('));

$('div').on('click', function(){

   if(typeof window[defaultFunctionName] ==="function")
   {
         window[defaultFunctionName]();
   }
    alert('Hello universe!');
});

It's just onclick attribute, no jQuery required:

<script>
    function f1(){ alert('hello world'); };
</script>

<a onclick="f1()" id="aa">test</a>
<a id="bb">test2</a>

<script>
    bb.onclick = aa.onclick;
    // or
    bb.onclick = function (){ alert('hello bb'); };   
</script>

Use this:

function f1() { 
    alert('hello world');
};
$('a').on('click', f1);

Here is your fiddle with the fix: http://jsfiddle/o8b5j15k/2/

Instead of attempting to copy the function bound inline, you could trigger the click event programatically:

function defaultFunction() {
    $("a[onclick]").click(); // change selector to match your actual element
}

http://jsfiddle/o8b5j15k/3/

Its best to use addEventListener() you can add all types of events. example: "click", "mousemove", "mouseover", "mouseout", "resize" and many more. the false at the end is to stop the event from traversing up the dom. If you want parent dom objects to also receive the event just change it to true. also this example requires no javascript libraries. This is just plain old javascript and will work in every browser with nothing extra needed.

Also addEventListener() is better than onClick() as you can add an unlimited number of event listeners to a dom element. If you have an onClick() on an element and then set another onClick() on the same element you have overwritten the first onClick(). Using addEventListener() if i want multiple click events to trigger when i click on an element i can do it with no problem.

If you want data about the element that is triggering the event you can pass the event to the function. You will see in my example function(e) e is the event and you can use e or this to target the element that is being triggered. Using e or this i can also get more data about the triggered event. for example if the event was a mousemove or mouseclick i can get the x and y position of the mouse at the time of the event.

   <!DOCTYPE html>
    <html>
    <head>
    <title>exampe</title>
    </head>
    <body>
        <a id="test" href="">test</a>
    <script>
        document.getElementById("test").addEventListener("click",function(e){
            alert('hello world');
            alert('my element '+e);
            alert('my element '+this);
        },false);
    </script>
    </body>
    </html>

if you want to have addEventListener call a function just change the 2nd value to the function name like this.

document.getElementById("test").addEventListener("click",f1,false);

this will execute the function

function f1(){ ... }

When you want to remove an event listener just call target.removeEventListener(type, listener[, useCapture]). Very simple and easy to manage.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744715476a4589593.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信