最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - calling a function before onclick script - Stack Overflow

programmeradmin3浏览0评论
<a href="#" onclick="foo()">click me </a>

Hello, I need to called a function before calling the onclick script when the is clicked.

I tried:

    var script = $("a").attr("onclick");
    $("a").attr("onclick", "");

    $("a").click(function(event) {
       // call bar() first, then foo();
       bar();
       // script is a string on Chrome
       // foo() may use this, so can not globalEval.
    });

how to call the script? Can I get the onclick as jQuery function? so that:

 onclickFunction.call(this);

Thanks.

<a href="#" onclick="foo()">click me </a>

Hello, I need to called a function before calling the onclick script when the is clicked.

I tried:

    var script = $("a").attr("onclick");
    $("a").attr("onclick", "");

    $("a").click(function(event) {
       // call bar() first, then foo();
       bar();
       // script is a string on Chrome
       // foo() may use this, so can not globalEval.
    });

how to call the script? Can I get the onclick as jQuery function? so that:

 onclickFunction.call(this);

Thanks.

Share Improve this question asked Nov 19, 2014 at 1:02 eastwatereastwater 5,65014 gold badges72 silver badges149 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

If you must follow this way try this:

JS:

(function() {
    var a = document.getElementsByTagName('a')[0];
    var foo = a.onclick;

    function bar() { console.log('bar'); } 

    a.onclick = function() {
        bar(); 
        foo();
    };
})();

jsfiddle

You can add "mouse up" or "mouse down" event to the element, this event will call before the "click" event call. Here is the demo.

void function(){
  $("div").mousedown(function(){
  console.log("mouse down event") 
  })
  $("div").mouseup(function(){
  console.log("mouse up event") 
  })
  $("div").click(function(){
  console.log("click event") 
  })
}();
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>click me</div>

can't you wrap them inside another function like this? :

<a href="#" onclick="handler();">click me </a>

var handler = function() {
   foo(); // 1. calling foo first
   bar(); // 2. calling bar second
};
发布评论

评论列表(0)

  1. 暂无评论