Javascript - 分配href

时间:2015-10-15 12:32:07

标签: javascript html

我正在尝试将href分配给div元素,但代码不分配href。知道为什么吗?

<div id="AllSearch" > Search All </div>
<script type="text/javascript">
function getQueryVariable(variable)
{
       var query = window.location.search.substring(1);
       var vars = query.split("&");
       for (var i=0;i<vars.length;i++) {
               var pair = vars[i].split("=");
               if(pair[0] == variable){return pair[1];}
       }
       return(false);
}

alert(getQueryVariable("k"));
var strurl = "http://search.Zark.it/pages/results.aspx?k=";
var urlEverything = strurl.concat(getQueryVariable("k"));
alert (urlEverything);
var x = document.getElementById("AllSearch");
//document.getElementById("AllSearch").href = "http://www.cnn.com";
x.href = urlEverything;
</script>

3 个答案:

答案 0 :(得分:0)

div元素没有href属性,但a元素

div的{​​{3}}和a的{​​{3}}

答案 1 :(得分:0)

如果您希望div可以点击,可以将其放在a标记内。 然后更改a代码的href属性的值:

document.getElementById('link').href = 'changed';
<a id='link'><div>hello</div></a>

答案 2 :(得分:0)

您可以使用setAttribute

&#13;
&#13;
document.getElementById('link').setAttribute("href", "www.google.com")
&#13;
<a id='link'>a's href was changed</a>
&#13;
&#13;
&#13;