标签onclick中的JavaScript代码

时间:2013-01-25 11:26:50

标签: javascript

我需要做一些丑陋的事情。但我不能以另一种方式做到这一点。我需要的是

<a href='some/url/?with&params' onclick="(if confirm('Do you wanna submit?')
    {some code to submit form in href property})">  

但我不知道如何使内联脚本工作......我对使用window.location或document.location提交它的方式犹豫不决。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

试试这个:

on html:

<a href='some/url/?with&params' onclick="if (confirm('Do you wanna submit?')) return MyValidation.actionSubmit();">Submit</a>

<script type="text/javascript" src="myValidation.js" />

<强> myValidation.js

我在这个答案中使用了

; //starts with this to close other js not yet closed
var MyValidation = {

    actionSubmit : function() {

            //your code go here

            //example of calling another function
            MyValidation.anotherFunction();

            //example of accessing a global variable (for your validation)
            MyValidation.variable;

            //example of declaring local variable
            var word = "hello";

            //example of calling another function with parameters
            MyValidation.anotherFunctionWithParameters(word, MyValidation.variable);

            //the returning
            return MyValidation.someValidation(word);
    }

    //Yes, this is a comma. 
    //I'm putting in the beginning so we see this and didn't forget :)
    ,anotherFunction : function() {

            //some code
            //maybe a return
    }

    ,variable : {}

    ,anotherFunctionWithParameters : function(param1, param2) {

            //more code, maybe a return
    }

    ,someValidation : function(parameter) {
        //some validation
        return true|false;
    }

};

看看这个:

  1. How do JavaScript closures work?

答案 1 :(得分:0)

你听说过AJAX吗? Google,如果你不这样做。 onClick参数接受带或不带参数的函数名,而不是“内联脚本”。

<script type=text/javascript>
  function doStuff(){
      if(confirm("Submit?"){
       //do your stuff with AJAX to some/url/?with&params

     }
  }
</script>
<a href='javascript:doStuff'>link</a>