jQuery 在页面加载时触发按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8840044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 11:07:06  来源:igfitidea点击:

Trigger a button on page load

jquerybuttontriggerstoggleslide

提问by Jamison

I have this function

我有这个功能

$("a#<?php echo $custom_jq_settings['toggle']; ?>").click(function() {
        jQuery("#<?php echo $custom_jq_settings['div']; ?>").slideToggle(400);
        jQuery("#featurepagination").toggle();
        jQuery("#featuretitlewrapper").toggle();
        return false;
    });

And this is the button I want to trigger on page load

这是我想在页面加载时触发的按钮

<a href="#" id="featuretoggle" onclick="changeText('<?php if (is_front_page()) {?>Show<?php } else { ?>Show<?php } ?> Features');"><?php if (is_front_page()) {?>Hide<?php } else { ?>Hide<?php } ?> Features</a>

I would like to trigger that button when the page loads so that it starts open but then slides/closes

我想在页面加载时触发该按钮,以便它开始打开但随后滑动/关闭

回答by Aknosis

Does this not work?

这不起作用吗?

<script>
    jQuery(function(){
      jQuery('#featuretoggle').click();
    });
</script>

回答by Adaz

That's the easiest way:

这是最简单的方法:

<script>
    $(function() {
        $("#featuretoggle").trigger("click");
    });
</script>

回答by David

You can trigger a click eventmanually with jQuery:

您可以使用 jQuery 手动触发点击事件

$('#featuretoggle').click();

To do this when the page loads:

要在页面加载时执行此操作:

$(document).ready(function() {
    $('#featuretoggle').click();
});

I imagine you'll want this to be the last thing to happen when loading the page, so make sure it's the last line to be executed within $(document).ready().

我想您会希望这是加载页面时发生的最后一件事,因此请确保它是在$(document).ready().

See this example:

请参阅此示例

<a href="#" id="someButton">Foo</a>
<script type="text/javascript">
    $(document).ready(function() {
        // bind the click event
        $('#someButton').click(function() {
            alert('baz');
        });

        // trigger the click event
        $('#someButton').click();
    });
</script>

回答by Shwet

What you want is can be achived by using setTimeout() function.

你想要的是可以通过使用 setTimeout() 函数来实现。

$(document).ready(function() {
    setTimeout(function() {
        $("a#<?php echo $custom_jq_settings['toggle']; ?>").trigger('click');
    },10);
});

This will work for you surely...

这肯定对你有用......