如何让jQuery在当前选项卡中打开页面而不是新页面

How to get jQuery to open a page in the current tab rather than a new one

本文关键字:新页面 jQuery 选项      更新时间:2023-09-26

在说答案已经在论坛上之前,请注意我已经尝试过它们无济于事。基本上问题是,当我按回车键搜索时,它会在新选项卡中打开谷歌页面。如何让它在当前选项卡中打开?

这是 HTML

<div class="Search">
    <img id="pic" src="http://i.imgur.com/fjAZgqe.png" alt="moose"/>
    <form class="websearch">
        <input autofocus placeholder="Google" type="text" id="GGLSite"> <!--this   creates the textbox they can use to search. Note the ID is what   the function grabs -->  
        <input type="button" id="GGLmeme" onclick="DoGGL()" style="display: none;" value="Search GGL"> <!-- this is just the button that calls the   function. The value is whats shown on the button --> 
    </form>
</div>

这是Javascript

function DoGGL(){  
    var GGLVar = document.getElementById("GGLSite").value; //this grabs the variable (search terms) from the textbox  
    var NewURL = "https://www.google.se/?gws_rd=ssl#safe=off&q=" + GGLVar; //this puts the site they typed into the wayback machines URL  
    var NewTabGGL = window.open(NewURL, "_blank"); //this opens a new tab with the URL.   
    if (NewTabGGL){ //make sure the browser can allow it   
        NewTabGGL.focus(); //switches them to the new tab -- done!  
    }  
    else{  
        alert("Popup didnt work");  
    }  
}
$(document).ready(function(){
    $('#GGLSite').keypress(function(e){
      if(e.keyCode==13)
        $('#GGLmeme').click();
    });
});

我对你的代码做了一些调整(阅读评论):

爪哇语

// Remember capitalized functions are supposed to be used with the new operator, hence, this function must not be capitalized
function doGGL(event){
    // Here we prevent the default behavior of the form submit
    event.preventDefault();
    // Javascript variables must not be capitalized
    var gGLVar = document.getElementById("GGLSite").value;
    var newURL = "https://www.google.se/?gws_rd=ssl#safe=off&q=" + gGLVar;
    // This sentence navigates to desired URL in the same window
    window.location.href = newURL;
}
$(document).ready(function(){
  // There's no need to catch the enter key because that's the form default behavior. So I'm attaching the submit event to the function defined above
  $('.websearch').on('submit', doGGL);
});

这在jsFiddle中不起作用,所以我在一个名为index的本地文件中尝试了它.html使用相同的HTML,CSS,但用后者替换了javascript。

希望对您有所帮助!

如果您尝试从此页面访问该页面,window.location = NewURL; 将起作用。我不明白你想做什么。