【问题标题】:Anchor tag not Triggering click event锚标记未触发点击事件
【发布时间】:2012-06-15 04:33:49
【问题描述】:

这里是DEMO
HTML 代码为

<div id="me"></div>

<a id="ok" href="">OK</a>

jquery 代码:

var tr = '';
for (var i = 0; i < 100; i++) {
    tr += '<tr><td>a' + i + '</td></tr>';
}
var table = '<table>';
table += tr;
table += '</table>';
$('#me').append(table);

$('td').each(function(index, value) {
    if ($(this).text() == 'a50') {
        $(this).addClass('yellow').attr('id', 'search');
    }
});    
$('#ok').attr('href','#search');
$('#ok').trigger('click');

TO DO:在每个 td 的表中都有数据。我正在尝试搜索数据。如果找到搜索数据,则添加td,属性class为黄色,id为搜索。 我有一个锚标签。锚标签是模拟的:当它被点击时,窗口将滚动到那个位置。我还添加了锚标签的内部链接。

现在,要点击 Anchor 标记,以便页面导航到 href 位置

问题 页面没有导航到内部链接。锚标签不触发点击有什么问题吗?但是当我用鼠标单击锚标记时导航

【问题讨论】:

  • 为什么不直接使用 window.location.href="#search"?

标签: jquery eventtrigger


【解决方案1】:

点击和导航是有区别的。所以当它是锚标签中的href时,它更像是导航 试试这个fiddle

var tr = '';
for (var i = 0; i < 100; i++) {
    tr += '<tr><td>a' + i + '</td></tr>';
}
var table = '<table>';
table += tr;
table += '</table>';
$('#me').append(table);

$('td').each(function(index, value) {
    if ($(this).text() == 'a35') {
        $(this).addClass('yellow').attr('id', 'search');
    }
});

location.href='#search';

【讨论】:

    【解决方案2】:

    将最后一行替换为

    window.location.href='#search​​';
    

    为我工作:)

    【讨论】:

      【解决方案3】:

      我认为你应该使用window.location.href。请尝试以下操作:

      // define this click event for #ok
      
      $('#ok').on('click', function() {
          window.location.href = this.href
      });
      
      $('td').each(function(index, value) {
          if ($(this).text() == 'a50') {
              $(this).addClass('yellow').attr('id', 'search');
          }
      });
      $('#ok').attr('href', '#search');
      $('#ok').click(); // trigger the click
      

      DEMO

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-29
        • 2015-03-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多