Javascript - window.location.assign not working

醉酒当歌 提交于 2019-12-11 01:10:04

问题


I've a project where I scan a QR code, and it will then automatically print out information based on which code was scanned.

I have the scanner, and a printer. Each QR code is to correspond to a URL. I can get the scanner to fill an input field, and I can get an alert to show the information that was scanned. However, whenever I try to assign the URL it simply appends the information to the current URL, instead of replacing it.

I need it to replace the current URL. Does anyone know why it is doing this, and how to fix it?

<html>
<head><title>QR Printing</title></head>

<body onload="document.myform.mytextfield.focus();">

<form name="myform">
    <input type="text" name="mytextfield" onchange="checkForm()">
</form>

<script type="text/javascript" language="JavaScript">

function checkForm() { 
    var field1 = document.forms['myform'].elements['mytextfield'].value; 
    alert(field1);
    window.location.assign(field1);
}    

</script>

</body>
</html>

回答1:


Looks like the form is submitting. Cancel it.

<form name="myform" onsubmit="return false">



回答2:


You want:

window.location = field1;



回答3:


add return false; after window.location.assign(field1);

 <html>
<head><title>QR Printing</title></head>

<body onload="document.myform.mytextfield.focus();">

<form name="myform">
    <input type="text" name="mytextfield" onchange="checkForm()">
</form>

<script type="text/javascript" language="JavaScript">

function checkForm() { 
    var field1 = document.forms['myform'].elements['mytextfield'].value; 
    alert(field1);
    window.location.assign(field1);
    return false;
}    

</script>

</body>
</html>


来源:https://stackoverflow.com/questions/26936947/javascript-window-location-assign-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!