简体   繁体   English

javascript变量通过url传递

[英]javascript variable pass by url

<script language=JavaScript>

function add()
 {

***Z***=3025;
}
</script>
<form........>
<input type ="submit" onClick="add()"
</form>

<a herf="http://XXXXXXXX.co.uk/XXXX.qmd?pack_id=***Z***"></a>

need to put the Z***emphasized text*** value in the URL The value of z will be produce by another java script function ADD 需要在网址中放入Z ***强调文本***值z的值将由另一个Java脚本函数ADD产生

You want to set the value of Z in the add() function and pass that value to the querystring in the URL. 您想要在add()函数中设置Z的值,并将该值传递给URL中的querystring。 I assume you want a client side implementation here. 我假设您要在此处执行客户端。

It wont work that way because the variable Z is not recognized outside the <script> block, so the <A href> does not know of such a variable. 它不会那样工作,因为在<script>块之外无法识别变量Z ,因此<A href>不知道这样的变量。

What will work however, is if you create the whole URL within the function and submit it from within the function. 但是,如果在函数内创建整个URL并从函数内提交它,那么将起作用。

Your code will look like this: 您的代码将如下所示:

In the add() function, the URL is constructed and browser address is instantly changed to that location. 在add()函数中,将构造URL,并将浏览器地址立即更改为该位置。

<script>
function add()         { 

var Z="3025"; 
document.location="http://XXXXXXXX.co.uk/XXXX.qmd?pack_id="+Z;
} 
</script> 
<form> 
    <input type ="submit" onClick="javascript:add()" value="my button"> 
    </form>

If you actually want to just set the variables into the <A href> so that these can be clicked by the user at a later time, you'll probably need to use some not recommended techniques such as document.write of the full url. 如果您实际上只是想将变量设置为<A href>以便用户以后可以单击它们,则可能需要使用一些不推荐的技术,例如完整URL的document.write

Read the above link for why not to go down that route. 阅读以上链接,了解为什么不走那条路线。

The best would be generating this at the server side, so that html is ready and no manipulation in JavaScript is needed. 最好的办法是在服务器端生成此代码,这样就可以准备html,并且不需要用JavaScript进行操作。 However: 然而:

give id to your link: 为您的链接提供ID:

<a href="http://XXXXXXXX.co.uk/XXXX.qmd?pack_id=" id="cool_link"></a>

and change its href attribute: 并更改其href属性:

<script>
    var Z = 3025;
    document.getElementById("cool_link").href += "***" + Z + "***";
</script>

if you're using jQuery syntax may be simplified a bit. 如果您使用的是jQuery语法,则可能会简化一些。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM