2012-06-15 196 views
3

這裏是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作爲黃色添加屬性類,並將id添加爲搜索。 我有一個錨標籤。錨點標籤用於模擬:單擊時,窗口將滾動到該位置。我還添加了到錨點標籤的內部鏈接。現在

,錨標記被點擊,這樣的頁面瀏覽到HREF位置

問題該頁面未導航到內部鏈接。錨標記沒有觸發點擊是否存在問題?但是當我點擊的錨標記與鼠標

+1

爲什麼不只是使用window.location.href = 「#搜索」? – Anonymous

回答

1

有點擊之間的差異和navigate..so當它被導航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'; 
+0

謝謝。這在Mozilla Firefox中正常工作,但不在Opera中。 – mesimplybj

1

最後一行替換爲

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

作品對我來說:)

+0

謝謝。這在Mozilla Firefox中正常工作,但不在Opera中。 – mesimplybj

1

我認爲你應該使用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

+0

謝謝。這在Mozilla Firefox中正常工作,但不在Opera中。 – mesimplybj