get the value of “onclick” with jQuery?

前端 未结 6 647
耶瑟儿~
耶瑟儿~ 2020-12-09 15:16

Is it possible to get the current value of the onClick attribute of an A tag via jQuery?

For example, I have:



        
相关标签:
6条回答
  • 2020-12-09 15:48

    Could you explain what exactly you try to accomplish? In general you NEVER have to get the onclick attribute from HTML elements. Also you should not specify the onclick on the element itself. Instead set the onclick dynamically using JQuery.

    But as far as I understand you, you try to switch between two different onclick functions. What may be better is to implement your onclick function in such a way that it can handle both situations.

    $("#google").click(function() {
        if (situation) {
            // ...
        } else {
            // ...
        }
    });
    
    0 讨论(0)
  • 2020-12-09 15:53

    i have never done this, but it would be done like this:

    var script = $('#google').attr("onclick")
    
    0 讨论(0)
  • 2020-12-09 15:55
    $('#google').attr('onclick') + ""
    

    However, Firebug shows that this returns a function 'onclick'. You can call the function later on using the following approach:

    (new Function ($('#google').attr('onclick') + ';onclick();'))()
    

    ... or use a RegEx to strip the function and get only the statements within it.

    0 讨论(0)
  • 2020-12-09 15:55

    I'm not quite sure how to do this in jQuery... but this works:

    var x = document.getElementById('google').attributes;
    for (var i in x) {
     if (x[i].name == "onclick") alert(x[i].firstChild.data);
    }
    

    but like Harshath said it would be better if you used event listeners, as removing and adding this function back into the onclick event may be troublesome.

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

    mkoryak is correct.

    But, if events are bound to that DOM node using more modern methods (not using onclick), then this method will fail.

    If that is what you really want, check out this question, and its accepted answer.

    Cheers!


    I read your question again.
    I'd like to tell you this: don't use onclick, onkeypress and the likes to bind events.

    Using better methods like addEventListener() will enable you to:

    1. Add more than one event handler to a particular event
    2. remove some listeners selectively

    Instead of actually using addEventListener(), you could use jQuery wrappers like $('selector').click().

    Cheers again!

    0 讨论(0)
  • 2020-12-09 16:13

    This works for me

     var link_click = $('#google').get(0).attributes.onclick.nodeValue;
     console.log(link_click);
    
    0 讨论(0)
提交回复
热议问题