简体   繁体   English

单击已经具有onClick的按钮

[英]Clicking on a button that has onClick already on

I know this sounds silly, but I need to create a function that finds a button that has onClick attached to it. 我知道这听起来很愚蠢,但是我需要创建一个函数来查找附加了onClick的按钮。 And then clicks it. 然后单击它。

So like: 像这样:

<div onclick="coolFunction()" class="coolClass">
   <p>Click Me!</p>
</div>

I tried searching for it by doing something like this: 我尝试通过执行以下操作来搜索它:

$('.coolClass').attr('onClick') == 'coolFunction()'

Which did actually find it, the problem is I don't understand how can I click on it because it's in an if method. 哪一个确实找到了它,问题是我不知道如何单击它,因为它在if方法中。

Your selector would be something more like $('[onclick="coolFunction()"]') . 您的选择器将更像$('[onclick="coolFunction()"]')

So to do what you describe, you could do this 因此,按照您的描述进行操作即可

 $('[onclick="coolFunction()"]').trigger('click');

Although, unless coolFunction() cares about being explicitly by this DOM element, you could just call coolFunction() , without having it piggy-back on your click handler. 虽然,除非coolFunction()关心是否由此DOM元素显式,否则您可以直接调用coolFunction() ,而不必将其搭载在点击处理程序上。

Update: With an argument 更新:带有一个参数

 // Note selector is less specific, but still targeted
 $('[onclick^="coolFunction"]').trigger('click');

With, this, you can trigger the click handler, and coolFunction(var) in your HTML would work as expected. 这样,您可以触发单击处理程序,并且HTML中的coolFunction(var)将按预期工作。

if ( $('.coolClass').attr('onClick') == 'coolFunction()' )
{
    $('.coolClass').click();
}
$('.coolClass').each(function() {
    $this = $(this);
    if ($this.attr('onClick') == 'coolFunction()') {
        $this.trigger('click')
    }

});

This will select all elements with .coolClass, check if the onClick attribute matches the coolFunction call and trigger the click event on that element. 这将选择所有带有.coolClass的元素,检查onClick属性是否与coolFunction调用匹配,并触发该元素上的click事件。

As couzzi said, you can first verify if all the elements of the class coolClass have the attribut coolFunction and when it's the case you can just apply what you want to do on them. 正如Couzzi所说,您可以首先验证类coolClass的所有元素是否都具有属性coolFunction ,在这种情况下,您可以仅对它们应用您想做的事情。

$('.coolClass').each(function() {
$this = $(this);
if ($this.attr('onClick') == 'coolFunction()') {
    $this.trigger('click')
}

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

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