Javascript onclick

后端 未结 4 1842
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-16 14:42

I have code like

test

Later on code is added to the same anchor tag like

相关标签:
4条回答
  • 2021-01-16 14:47

    You could try this:

    var lnk = document.getElementById('lnk1'); // don't forget var!
    
    var oldHandler = lnk.onclick;
    lnk.onclick = function(ev) {
      if (oldHandler) oldHandler(ev);
      // do something ...
    };
    

    That code saves a reference to the old handler, and if it's not empty it calls it before doing whatever else the new handler wants to do.

    You could put the call to the old handler after the new code, or mixed in, or whatever.

    0 讨论(0)
  • 2021-01-16 14:52

    You have a mistake in your statement:

    JAVASCRIPT

    lnk = document.getElementById('lnk1')
    lnk1.onclick = function() { do something} \\ replace lnk1 with lnk
    lnk.onclick = function() { do something} \\ this will work
    

    You have defined lnk as variable but your are calling lnk1 with onclick event. This is a wrong statement.

    USE HTML

    <a id='lnk1'>test</a>
    

    See the Demo: http://jsfiddle.net/tm5cX/

    0 讨论(0)
  • 2021-01-16 14:56
    <a id='lnk1' onclick='do something' >test</a>
    

    JavaScript

     lnk1 = document.getElementById('lnk1')
        lnk1.addEventListener('click',function() { do something}, false);
    

    when setting onclick you are overwrite existing attribute, but assign click through event listener then it will be ok.

    0 讨论(0)
  • 2021-01-16 15:08

    There is a very simple, standards-compliant way to do this:

    lnk1.addEventListener('click', function() {
        // do something
    });
    

    This doesn't work in IE before version 9, so you'll need to do this:

    var handler = function() {
        // do something
    };
    
    if ("addEventListener" in lnk1) { // standards-compliant browsers
        lnk1.addEventListener('click', handler);
    } else { // Internet Explorer < v9
        lnk1.attachEvent('onclick', handler);
    }
    

    This will work, and both the original function specificed in the HTML attribute and in the code above will run. HOWEVER it would be far nicer to define all your event handlers in the same place: in the Javascript. Think hard about removing event handling logic from your HTML attributes.

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