简体   繁体   English

如何使用jQuery选择并单击

[英]How do I select and click using jQuery

<div id="subNav-Requests" class="suit-sub-nav" style="">
  <ul class="page-container">
    <li>
    <a class="navLink0" href="/MyApp/reporting/list/data.do">
        <span>Report Data</span>
    </a>
    </li>
  </ul>
</div>

I have a code like this. 我有这样的代码。 I am trying to simulate a click on 'Report Data' . 我试图模拟'Report Data'的点击。 What I am trying is 我在想的是

var nav = 'div#subNav-' + mainNavId; //results in 'div#subNav-Requests'
$(nav+' a.navLink0').trigger('click'); 

No errors, nothing happens. 没有错误,没有任何反应。 I also tried this 我也尝试过这个

$('a.navLink0').trigger('click'); 

to the same effect. 达到同样的效果。 I have to select the subNav-Requests because there are many more like that, for Eg subNav-Reports , subNav-Allergies etc. with the same structure but with many navLinks inside. 我必须选择subNav-Requests因为还有更多类似的东西,例如subNav-ReportssubNav-Allergies等,具有相同的结构但内部有很多navLinks

Calling click on an element just executes any event handlers attached to the element. 调用单击元素只会执行附加到元素的任何事件处理程序。 It will not send the browser to the href of an a tag. 它不会将浏览器发送到标签的href。 To do that the best I can think of is: 要做到这一点,我能想到的最好的是:

var href = $('a.navLink0').attr('href');
window.location.href = href;

Does that meet your need? 这符合您的需求吗?

请尝试$('a.navLink0', nav).click();

As far as i know you cant simulate an actual click on the link, what you are doing is simply triggering a click event, but that isnt enough. 据我所知,你无法模拟链接上的实际点击,你所做的只是触发点击事件,但这还不够。

You could set a listener for the event by 您可以通过设置事件的侦听器

$('a.navLink0').click(function() {
    window.location = $(this).attr("href");
});

and then triggering the click event, but why are you doing this? 然后触发click事件,但你为什么要这样做呢? wouldnt a redirect fit your purpose better? 不会重定向更符合您的目的吗?

window.location = $('a.navLink0').attr("href");

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

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