How to simulate anchor link click

前端 未结 6 654
渐次进展
渐次进展 2020-12-15 04:02

I\'m trying to trigger a link click for .jquery. Does someone know why the following doesn\'t work.



        
相关标签:
6条回答
  • 2020-12-15 04:29

    Looks like your $("google_link_proxy") selector is off. Try $("#google_link_proxy").

    You also need to close the observe call with }).

    Those are the syntax errors with the code above though I don't think those functions are provided in jQuery by default.

    Here is what I think you're after:

    $("#google_link_proxy").click(function(event){
        window.open($("#google_link").attr('href'),'_blank')
    });
    
    0 讨论(0)
  • 2020-12-15 04:29

    If you use jQuery and the native DOM, the anchor can be clicked

    // insert an <a> into document and click it **natively**
    // (.get(0) returns the DOM element)
    $('<a id="fred99" />').attr('href', '#david').attr('target', '_blank')
    .text('LINK').appendTo('body').get(0).click();
    
    // now we've clicked, tidy up
    $('#fred99').remove();
    
    0 讨论(0)
  • 2020-12-15 04:34

    This can be done without jQuery:

    document.querySelector('#google_link').click()
    
    0 讨论(0)
  • 2020-12-15 04:37

    The jQuery method completely ignores href:

    $('#google_link').click(); // ignores href!
    

    The native DOM method does the right thing:

    $('#google_link')[0].click();
    

    This works regardless of whether the href is a URL, a fragment (e.g. #blah) or even a javascript:.

    0 讨论(0)
  • 2020-12-15 04:43

    Make sure you have your jQuery code wrapped in a ready block like so

    $(document).ready(function(){/* your code here */});
    

    This ensures scripts are fired after all the content and images are loaded.

    0 讨论(0)
  • 2020-12-15 04:43

    Use click()

    $("#google_link_proxy").click(
        function(){
            $("#google_link").click();
        }
    );
    

    fireEvent and observe is not part of jQuery API

    0 讨论(0)
提交回复
热议问题