2012-03-22 174 views
0

我在JavaScript中有一个变量,其中包含图像的目录。 我想把它传递给href 如何做到这一点?将变量从javascript传递给href

function OpenNewWindow(n, width, height) 
    { 
      if(navigator.appName == "Microsoft Internet Explorer"){ 
      xhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
      xhttp.open("GET","http://www.multimediaprof.com/test/emp2.xml",false); 
      } 
     else if(navigator.appName == "Netscape"){ 

     xhttp=new XMLHttpRequest(); 
     // alert("step 1"); 
     xhttp.open("GET","xml/emp2.xml",false); 
     } 
     xhttp.send(""); 
     xmlDoc=xhttp.responseXML; 

var imageName = xmlDoc.documentElement.childNodes[n].textContent; 
TestP[n] = imageName; 
alert(TestP[n]); 
var img = document.createElement('img'); 
img.src = "pic/" + imageName; 
alert(img.src); 
return img.src; 

<li><a href="javascript:OpenNewWindow(1,000,000);alert('clicked!');" rel="shadowbox" ">Part 0</a></li> 

变量img.src包含路径,我想将它传递给HREF

+3

请提供一些您的代码。 – Oyeme 2012-03-22 07:10:09

+0

将你的接受程度提高到绿色水平 – 2012-03-22 07:11:17

+1

你[第一次问它]是什么问题(http://stackoverflow.com/questions/9804790/passing-javascript-variable-to-href)? – Neysor 2012-03-22 07:13:18

回答

0

那么,它真的不是必要的,因为你可以简单地触发window.location = 'http://whatever...';,你的页面会出现重定向。但是如果你想通过它,只需获取元素:var a = document.getElementById('yourelementid');然后将你的变量赋值给它:a.setAttribute('href',yourvariable); ..

+0

我试过了,但它没有工作..任何想法? – 2012-03-22 08:18:28

+0

是的。我不想听起来很吝啬,但是你的代码看起来像你复制粘贴某些东西而不知道它是什么意思,从语法错误开始,比如甚至没有关闭函数等等。我推荐的唯一的东西是学习一些$ .ajax和jQuery一般来自http://jquery.com – lu1s 2012-03-22 20:04:08

0

如果你有这样的元素,这是你需要做的。

<a id="sample">My href</a> 

var url = 'your url'; 

您可以按如下方式分配变量。

$('#sample').attr('href',url); 

否则

$('#sample').attr('href') = url; 

我已经发布,根据你这并没有这么多的澄清您最初的问题,这个答案。

+0

你可以调整你的答案,以便它与我的代码兼容吗?我预先感谢你 – 2012-03-22 08:18:07

+0

我试过了,它没有任何想法? – 2012-03-22 08:36:02