Simulate click with jQuery after inserting link via jQuery

6

I have to open another tab with a link that is returnable from PHP to jQuery. I've used window.open but it asks to release popup and the client does not like it at all. So I thought of doing, when jQuery receives the link, it changes <a href="javascript:void(0);" target="_blank"></a> to <a href="http://www.LinkQueRetornou.com.br" target="_blank"></a> and performs a function to simulate a click to open in another tab. The problem is that I made the code below and it is not working because it does not open the page in another tab, now I do not know if it is because the link was added later in a jQuery (DOM) action.

HTML + jQuery

<button class="button" type="button" id="teste">Click</button>
<a href="javascript:void(0);" id="linkredirect" target="_blank"></a>

<script>
    $(document).ready(function(){

        $("#teste").click(function(){

            $("a#linkredirect").prop('href', 'http://www.google.com.br');
            $("a#linkredirect").trigger("click");
        })
    })
    </script>
    
asked by anonymous 25.11.2015 / 03:25

1 answer

5

Instead of using the $(seletor).trigger("click"); use $(seletor)[0].click(); .

Good, but why?

According to @The Alpha's response to this question , what happens is that in the case of the function trigger() the execution will not trigger a click event itself, but instead execute an event handler, if declared, such as:

$(selector).click(function() {
    // some code...
});

Okay, but why use [0] before .click(); ?

If it is necessary to use 0 in brackets, the click() function is native to javascript, so it does not belong to a jQuery object. If you do not use [0] to get only the HTML element the click() function will have the same functionality as trigger() .

This way your code will work.

$(document).ready(function(){
    $("#teste").click(function(){
        $("a#linkredirect").prop('href', 'http://www.google.com.br');
        $("a#linkredirect")[0].click();
    });
});
  

See also working on jsfiddle

    
25.11.2015 / 03:49