javascript - 如何解析并形成字符串以使用 Javascript 打开网页

标签 javascript string parsing forms

我有一个表单,我需要运行一些 JavaScript 来解析表单中存储的页面信息以打开它。

<script type="text/javascript">
function validateForm()
{
var x=document.forms["myForm"]["fname"].value
if (x==null || x=="")
  {
  alert("First name must be filled out");
  return false;
  }
}

function open()
{
     if (validateForm()) {
         1. get the value 
         2. parse the value to get year/month/date (?)
         3. compose the string of webpage (?)
         4. open the webpage (?)
     }
}
</script>

<form name="myForm" onsubmit="return open()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

输入的格式为2011/03/05,我需要打开http://abc/def/2011/03/2011_03_05.html。它需要解析日期,并附加字符串,然后打开页面。

答案

<script type="text/javascript">
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
  {
  alert("First name must be filled out");
  return false;
  }
  return true;
}

function openPage()
{   
     if (validateForm()) {
        var value = document.forms["myForm"]["fname"].value

        var strYear = value.substring(0,4);
        var strMonth = value.substring(5,7);
        var strDay = value.substring(8,10);

        var strURL = "http://abc/def/"+strYear+"/"+strMonth+"/"+strYear+"_"+strMonth+"_"+strDay+".html";
        alert("strURL");

        //document.location.replace(strURL)
        //document.write(strURL);
        window.open(strURL,"myWindow");
     }
}
</script>

<form name="myForm" onsubmit="openPage()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

最佳答案

假设输入始终为 yyyy/mm/dd 形式,则可以按如下方式解析字符串:

var strYear = fname.value.substring(0,4);
var strMonth = fname.value.substring(5,7);
var strDay = fname.value.substring(8,10);

var strURL = "http://abc/def"+strYear+"/"+strMonth+"/"+strYear+"_"+strMonth+"_"+strDay+".html";

// To change the same page with new URL, use:
  document.location.replace(strURL);
// To open a new popup window, use:
 window.open(strURL,"myWindow");

关于javascript - 如何解析并形成字符串以使用 Javascript 打开网页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5223310/

相关文章:

用于修改 CSS 的 Javascript 在 IE 中不起作用

javascript - 函数、表单和用户输入的数据

c - 如何在C语言中查找文本文件中的字符串?

json - 使用jq从Json子集合中查找和替换元素

javascript - 动态将属性附加到构造函数并在新对象实例中使用?

javascript - Cheerio .css([property]) 总是返回 null?

java - 将字符串转换为十六进制的字符集是什么?

javascript - 在Javascript中按空格和新行分割字符串

java - XML - 使用 DOM 解析元数据属性

python - 任何人都有一个使用 lxml.html 中的 element.sourceline 方法的示例