我想在链接中使用javascript vars

时间:2013-04-03 08:09:30

标签: javascript hyperlink

我正在使用以下javascript。但是输出是文本。我想要链接中的这个输出。

<script type="text/JavaScript">

  _url = document.location

  _picurl = "danny.jpg"

  _title = "Your Title Here"

  _desc = "Your Description Here"

 _fbshare ="http://fbshare.mobie.in/l"

  document.write( _fbshare + "?" + "site=" + _url + "&Pic=" + _picurl + "&Title=" + _title + "&Ds=" + _desc)

</script>

我想在链接中使用document.write( _fbshare + "?" + "site=" + _url + "&Pic=" + _picurl + "&Title=" + _title + "&Ds=" + _desc),但不知道。

2 个答案:

答案 0 :(得分:1)

而不是一些凌乱的document.write使用清洁方法并选择或创建锚并相应地设置它的属性。

此外,您无法通过document.write修改现有元素,您必须从dom中选择它,然后操纵它的属性。

正确的方法是,例如,如果您的html中已有链接:

<a id="link" href=""></a>

你的剧本:

var a = document.getElementById("link"); // or another equivalent method
a.innerHTML = 'linktext';
a.href = "#somelink";

或者如果链接尚不存在:

var a = document.createElement("a");
a.innerHTML = 'linktext';
a.href = "#somelink";
// insert into the document
document.body.appendChild(a);

See the example

答案 1 :(得分:0)

在您希望链接显示的位置添加以下元素:

<span id='mySpan'></span>

以下代码可以将您的链接放在此元素中:

<script language='javascript'>
_url = document.location;    
_picurl = "danny.jpg";    
_title = "Your Title Here";
_desc = "Your Description Here";    
_fbshare ="http://fbshare.mobie.in/l";
_linkTitle = "Link";

document.getElementById('mySpan').innerHTML="<a href='"+_fbshare + "?" + "site=" + _url + "&Pic=" + _picurl + "&Title=" + _title + "&Ds=" + _desc+"'>"+_linkTitle+"</a>";
</script>