javascript 页面加载时点击触发 (UL > LI)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22130984/
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-10-27 22:30:56  来源:igfitidea点击:

Click trigger on page load (UL > LI)

javascriptjqueryhtmlclickhtml-lists

提问by silviu.scr

I have the following HTML code in my website:

我的网站中有以下 HTML 代码:

<div id="gallery">
    <ul class="pictures">
        <li><a href="#" data-filter="*" class="active">All</a></li>
        <li><a href="#" data-filter=".web">Web</a></li>
        <li><a href="#" data-filter=".design">Design</a></li>
        <li><a href="#" data-filter=".video">Video</a></li>
    </ul>
</div>

And I want to have a click event triggering when the page loads. I want the first (or second) list item to be clicked when the page loads.

我希望在页面加载时触发点击事件。我希望在页面加载时单击第一个(或第二个)列表项。

I've tried with the following code, but I failed and I don't know how to do it:

我已经尝试过以下代码,但我失败了,我不知道该怎么做:

$("document").ready(function() {
    setTimeout(function() {
        $("ul.pictures li:nth-child(2)").trigger("click");
    },10);
});

采纳答案by Pete

Problem

问题

The code is triggering the "onclick" event on the li element. You want to trigger the "onclick" event on the "a" element.

该代码正在触发 li 元素上的“onclick”事件。您想在“a”元素上触发“onclick”事件。

Solution

解决方案

$('#gallery li:nth-child(2) a').click();

Example

例子

See jsFiddle

jsFiddle