Как автоматически перейти по URL-адресу, не нажимая на него

#javascript #html #url

#javascript #HTML #url

Вопрос:

Я нашел следующий скрипт в Интернете.

Как мне изменить код, чтобы при Open нажатии кнопки он переходил по адресу в lnk.href ( "https://www.google.si/maps/place/ljubljana" userInput; )

 <body>
<script type="text/javascript">
function changeText2(){
    var userInput = document.getElementById('userInput').value;
    var lnk = document.getElementById('lnk');
    lnk.href = "https://www.google.si/maps/place/ljubljana"   userInput;
    lnk.innerHTML = lnk.href; 
}
</script>
Type the location and click Open! <a href="" id=lnk>link</a> <br>
<input type='text' id='userInput' value='' />
<input type='submit' onclick='changeText2()' value='Open'/>
  

Ответ №1:

Вы хотите добавить window.location = lnk.href; в конце своей функции:

 <script>
function changeText2() {
    var userInput = document.getElementById('userInput').value;
    var lnk = document.getElementById('lnk');
    lnk.href = "https://www.google.si/maps/place/ljubljana"   userInput;
    lnk.innerHTML = lnk.href;
    window.location = lnk.href;
}
</script>

Type the location and click Open! <a href="" id=lnk>link</a> <br>
<input type='text' id='userInput' value='' />
<input type='submit' onclick='changeText2()' value='Open'/>
  

Вы также можете избавиться от ссылки:

 <script>
function openUrl() {
    var userInput = document.getElementById('userInput').value;
    window.location = "https://www.google.si/maps/place/ljubljana"   userInput;
}
</script>

Type the location and click Open!<br>
<input type='text' id='userInput' value='' />
<input type='submit' onclick='openUrl()' value='Open' />