【问题标题】:JavaScript code in a tag onclick标签中的 JavaScript 代码 onclick
【发布时间】:2013-01-25 11:26:50
【问题描述】:

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

<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 提交它的方式犹豫不决。有什么想法吗?

【问题讨论】:

  • 为什么需要这样做?在字符串中编写代码最终必然会带来问题。这将很难维护,并且您将无法使用 IDE 验证潜在的语法错误。
  • 我需要添加两个链接以使用给定的 url 提交表单...我收到了 onlu widjets 文件(django 应用程序).​​..我没有模板和表单源...
  • JavaScript 的伟大之处在于它很容易注入到其他环境中。只需添加您自己的脚本并等待 DOM 准备就绪,然后使用 jQuery 或其他方法来识别该 href(给它一个类/id)并使用 api.jquery.com/click 在回调中编写所有事件代码

标签: javascript


【解决方案1】:

试试这个:

在 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?

【讨论】:

  • 我试过这个...但它破坏了布局,我不知道为什么...也许我上次做错了什么。
  • 布局损坏?内联编码不会解决这个问题。发布您的 html+css+js,以便我们提供帮助。
  • 我发现了一个错误))这是我的错))))你给的代码工作正常!但是还有一个问题……如何通过给定的链接提交表单?有人建议我使用 window.location 但我是 javascript 的新手...
  • 嗯,这种问题很简单。在这种情况下,您应该先搜索。我发现这个答案here 涵盖了您的问题。问题本身有一个 jQuery 解决方案;尝试使用@hasen-j 的函数get_form,你会从中学到更多。
  • 但是,随着时间的推移,您将了解 Javascript 的工作原理,然后您将能够使用像 jQuery 这样的 API。见jquery
【解决方案2】:

您听说过 AJAX 吗?如果你不这样做,请谷歌它。 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>

【讨论】:

  • 我听说过,但如果表单没有返回任何内容,它会以正确的方式工作吗?
  • 您几乎可以将完整的 jquery 代码包含在 onclick 中(不要尝试 :)) - 它不仅限于函数名称。并不是说您应该在 onclick 中添加很多逻辑,只是澄清一下。
猜你喜欢
  • 1970-01-01
  • 2018-04-08
  • 2022-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-11
相关资源
最近更新 更多