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

时间:2016-02-23 21:53:36

标签: javascript jquery html

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

这是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();
    });
});

2 个答案:

答案 0 :(得分:0)

如果您尝试从此页面访问该页面,则window.location = NewURL;会工作。我不确切地知道你想要做什么。

答案 1 :(得分:0)

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

<强>的Javascript

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

希望它有所帮助!