3
votes

Here is the DEMO
HTML CODE as

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

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

jquery code:

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: In a table in each td there is data.I am trying to search the data. if the search data is found,the td is added with attribute class as yellow and id as search. I have an anchor tag. The anchor tag is to simulate: when it is clicked then the windows is to be scroll to that location.I also added internal link to anchor tag.

Now,the Anchor tag is to be click so that the page is navigate to href location

PROBLEM The page is not navigating to internal link. Is there any problem with anchor tag not triggering click? But is navigated when i click the anchor tag with mouse

3
Why don't just use window.location.href="#search"?Anonymous

3 Answers

1
votes

There is a difference between click and navigate..so when it is href in anchor tag, its more like navigating Try this 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';
1
votes

Replace the last line to

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

works for me :)

1
votes

I think you should use window.location.href. Try the following:

// 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