【问题标题】:Calling jquery function in the body在正文中调用 jquery 函数
【发布时间】:2013-12-08 12:23:43
【问题描述】:

我想调用这个jquery函数:

$(function() {
    if (window.location.href.toLowerCase().indexOf("gamila-secret") < 0) {
        window.location = window.location.href + '?gamila-secret';
    }
});

在我的正文中的 html 代码中,所以它会在这里:&lt;body onload="*call the function here*"&gt;
我试图给这个函数起一个名字,比如“reloader();”并在体内调用它,但我该怎么做呢?

【问题讨论】:

  • 使用就绪处理程序有什么问题?

标签: jquery


【解决方案1】:

你可以将它定义为函数,并以这种方式调用它,但这是一个非常糟糕的设计示例。

改为使用 $(document).ready(function(){...}) 语法。

标题或正文中的任何位置:

$(document).ready(function() {
  if (location.href.toLowerCase().indexOf("gamila-secret") < 0) {
    location = location.href + '?gamila-secret';
  }
});

如果这不适合你,你可以这样做:

window.app_my_listener = function() {
  if (location.href.toLowerCase().indexOf("gamila-secret") < 0) {
    location = location.href + '?gamila-secret';
  }
};
body onload="app_my_listener()"

但是请不要那样做。每次直接在html中注入javascript神杀小猫。

【讨论】:

  • 这对我没有帮助,我想在正文中调用它,我想使用onload=""
  • 用例是什么?为什么 $.ready() 形式不适合你?无论如何,我更新了答案。
【解决方案2】:

由你选择

在 html 中

<body onload="call()">

在 JS 中

<script>
function call()
{
  if (location.href.toLowerCase().indexOf("gamila-secret") < 0) {
    location = location.href + '?gamila-secret';
  }
}
</script>

但如果你使用 jQuery 是最好的选择

在 html 中

<body >
//no need to call function 

在 JS 中

$(document).ready(function() {
  if (location.href.toLowerCase().indexOf("gamila-secret") < 0) {
    location = location.href + '?gamila-secret';
  }
});

【讨论】:

    猜你喜欢
    • 2014-01-23
    • 1970-01-01
    • 1970-01-01
    • 2019-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多