How to get the onclick “attribute event” return value in “property event”?

北城以北 提交于 2019-12-24 07:50:15

问题


consider this code sample :

<a href="some url" onclick="confirm('ok to proceed ?')">bla</a>`

<script type="text/javascript">
    $(document).ready(function() {
              $("a").live("click", function (event) {
                    // In that function, I want to get 
                    // the "confirm" return value                  
               });
</script>

It is possible to get this return value without modifying the DOM ??

Thanks.............


回答1:


<a href="some url" onclick="var myVar = confirm('ok to proceed ?')">bla</a>

If I remember correctly, that should work. You would then have access to myVar in your jQuery block like you would have access to any other Javascript variable.




回答2:


No, the value is not stored anywhere for you to access. The only way to get that value is to move it to a jQuery handled click event like this:

$(document).ready(function() {
    // The removeAttr removes the original "onclick" attribute
    $("a").removeAttr('onclick').live("click", function (event) {
       var ret = confirm('ok to proceed ?');
       // Do what you want here because `ret` has the return 
       // value from the `confirm` call.
    });
});



回答3:


you need to explicitly add the word "return", like this:

onclick="return confirm('ok to proceed?')"

EDIT: my initial reply was BS, here's what I got to work finally.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script type="text/javascript" src="jquery-1.3.2.js"></script>
    <script type="text/javascript">
$(document).ready(function(){
    $("a").click(function() {
        var stuff = confirm('ok?');
        if (stuff) {
        alert('was ok, stuff=' + stuff);
        }
    else {
        alert('was not ok, stuff=' + stuff);
        }
    });
});
    </script>
  </head>
  <body>
    <a href="http://jquery.com/">jQuery</a>
  </body>
</html>



回答4:


getValueConfirm`

var isConfirm = false; function confirmDialog(){ isconfirm = confirm('ok to proceed ?'); } $(document).ready(function() { $("a").live("click", function (event) { alert(isconfirm);// your value that you want get it }); });



来源:https://stackoverflow.com/questions/1976118/how-to-get-the-onclick-attribute-event-return-value-in-property-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!