简体   繁体   English

如何调用jQuery函数,使其可以在document.ready函数中运行?

[英]How do I call my jQuery function so that it will run in my document.ready function?

In my application I have a script: 在我的应用程序中,我有一个脚本:

<script type="text/javascript">
function pageLoad(sender, args){
    $('#nursing').click(function () {
        document.getElementById("ddlPositionType").selectedIndex = 1;
        $("#btnSearch").click();
        a.href = "#";
        return false;
    });
}
</script>

Then below it I am attempting to call it when the page is loaded like this: 然后在它下面,我试图在页面加载时像这样调用它:

<script type="text/javascript">
$(document).ready(function () {
    $('#nursing').click();
});
</script>

This does not fire when the page load as it should and it causes no errors in my console. 页面加载时不会触发,也不会在我的控制台中导致任何错误。 What is most confusing is that if I took from document to return false from the first code block and placed it where I am trying to call the $('nursing').click(); 最令人困惑的是,如果我从document中取出第一个代码块中的return false并将其放置在我试图调用$('nursing').click(); the code will run like it is supposed to. 代码将按预期运行。

As reference #nursing is simply a link used on my slider to control content. 作为参考, #nursing只是我的滑块上用来控制内容的链接。

<a id="nursing" class="oslide">Nursing Positions</a>

The code you've written in pageLoad is an instruction to set up a click handler. 您在pageLoad中编写的代码是设置点击处理程序的指令。 That setup will not be executed unless the pageLoad function is called prior to your call to click the button in document.ready. 除非在您单击document.ready中的按钮之前调用pageLoad函数,否则不会执行该设置。 The easy fix may be to simply modify your code so that it calls pageLoad, and then clicks the anchor. 简单的解决方法可能是简单地修改您的代码,使其调用pageLoad,然后单击锚点。

<script type="text/javascript">
$(document).ready(function () {
    pageLoad();
    $('#nursing').click();
});
</script>

But this seems a lot of overkill to call a function by performing a click. 但这似乎是通过单击来调用函数的过大杀伤力。 Why not just make a function out of the click handler and call that code in document.ready instead? 为什么不只是在点击处理程序中创建一个函数,然后在document.ready中调用该代码呢? If you still need the click handler, call the function in the click handler. 如果仍然需要单击处理程序,请在单击处理程序中调用该函数。

function onNursingClick() {
    document.getElementById("ddlPositionType").selectedIndex = 1;
    //... and so on....
}

function pageLoad() {
    $("#nursing").click(onNursingClick);
}

$(function() {  //shorthand for $(document).ready(...);
   onNursingClick();
   pageLoad();
})

It's not working because in your document.ready script you're not calling the function pageLoad() that you created earlier. 它不起作用,因为在document.ready脚本中,您没有调用先前创建的函数pageLoad()。 You are firing a click event. 您正在触发点击事件。 So try this: 所以试试这个:

<script type="text/javascript">
    $(function(){     //Jquery shorthand for document.ready
        pageLoad(sender, args); //pass in what you need
    });
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM