2012-09-29 119 views
2

我是初学者!我需要的是这样的:有没有办法通过命令行将字符串传递给html javascript?

C:\MyHtmlPage.html "string_that_I_need_to_pass_to_the_javascript_code_inside_MyHtmlPage" 

,并把 “string_that_I_need_to_pass_to_the_javascript_code_inside_MyHtmlPage” 里面:

var externalstring 

是否有类似做什么? 谢谢!

编辑:

我找到了方法! 内部DOS命令行我写的:

start firefox "file:///C:/MyHtmPage.html?externalstring=string_that_I_need_to_pass_to_the_javascript_code_inside_MyHtmlPage" 

而且在JavaScript我添加此(http://papermashup.com/read-url-get-variables-withjavascript/):

var externalstring = getUrlVars()["externalstring"]; 
alert(externalstring); 

function getUrlVars() { 
var vars = {}; 
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, 
function(m,key,value) { 
    vars[key] = value; 
}); 
return vars; 
} 

谢谢你所有的建议! =)

+0

你为什么想这样做? – Erwin

回答

1

没有,但如果你是加载它在浏览器中,你可以使用一个fragment identifier

像这样:

<a href="file:///C:/MyHtmPage.html#string_that_I_need_to_pass_to_the_javascript_code_inside_MyHtmlPage">CLICKY</a> 

,然后在javascript:

console.log(window.location.hash); 
2

你可以使用像这样的查询参数:

C:\MyHtmlPage.html?parm=string_that_I_need_to_pass_to_the_javascript_code_inside_MyHtmlPage 

然后,在您的页面javascript中,您可以使用window.location.search来检索parm = xxxx片断,并在需要时解析出xxx。如果需要,这种格式允许您传递多个不同的参数。这是将多个参数嵌入到URL中的通用方式。然后,如果URL来自Web服务器,则可以通过页面中的javascript或服务器解析出它们。

相关问题