jQuery jQuery触发点击第一个孩子

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

jQuery trigger click on first child

jquerytriggersclick

提问by Alex

I'm trying to invoke a click on first .loaderchild when document is ready, but no success:

我试图.loader在文档准备好时调用第一个孩子的点击,但没有成功:

html:

html:

<a class="loader" data-target="david-boy" title="Danny Boy-Rivera">
    <span class="img"><span class="play"></span><img src="img/gallery-image1.jpg" alt="" /></span>
    <h2>Danny Boy</h2>
</a>

jQuery:

jQuery:

//Does not work
$('a.loader:first-child').bind('click');
$('a.loader:first-child').trigger('click');
$('a.loader:first-child').click();
//Works
$('a.loader:first-child').css("background", "red");

Any ideas why?

任何想法为什么?

Update

更新

Handler:

处理程序:

$('.loader').click(function(){
    var name=$(this).data("target");
    callVideo(name);
});

Update2

更新2

So the problem was that I had declared the :first-childaction before the handler. I changed their places and everything ok

所以问题是我:first-child在处理程序之前声明了这个动作。我改变了他们的位置,一切正常

回答by Likwid_T

Did you define the handler beforeyou initiated the triggered 'click'?

您是否启动触发的“点击”之前定义了处理程序?

Here's the EXACT same code from your fiddle except I put the handler BEFOREthe trigger

这是您小提琴中的完全相同的代码,除了我将处理程序放在触发器之前

$(document).ready(function(){
    $('.loader').click(function(){
       alert($(this).data("target")); 
    });
    $('.loader:first-child').click();
    $('.loader:first-child').css("background", "red");
});?

This will pop the alert you're looking for

这将弹出您正在寻找的警报

回答by gdoron is supporting Monica

You need to have a handler to the click event...

你需要有一个点击事件的处理程序......

$('a.loader:first-child').click(function(){
    alert('clicked');
});

$('a.loader:first-child').click();


Update:

更新:

You're handler was probably attached before the element was ready.

在元素准备好之前,您的处理程序可能已附加。

$(function(){
    $('.loader').click(function(){
        var name=$(this).data("target");
            callVideo(name);
    });
});