使用javascript将变量放入href中

时间:2015-02-17 13:41:29

标签: javascript jquery

这与此问题(已经解决)相关:Previous Problem:Solved,只是为了提出问题的背景。

我想要做的是将我从前面的代码中获得的链接应用到按钮元素中的href中。这是我到目前为止所得到的:

<script type="text/javascript">
var newestLink = "";
window.setTimeout(function(){
    var newLink = $('.link:last').attr("href");
    newestLink = newLink;
}, 1500);

window.setTimeout(function(){
alert(newestLink);
document.getElementById('#redButton').onClick = function() {
  document.getElementById('#redButton').href=newestLink;
}
}, 3000);
</script>

alert代码只是检查我是否有正确的值。当我使用此代码时,控制台会返回错误Uncaught TypeError: Cannot set property 'onClick' of null (anonymous function)

我似乎无法理解代码出错的地方。我跟随this advise

3 个答案:

答案 0 :(得分:3)

你混淆了javascript和jQuery语法。 Javascript是document.getElementById('redButton'),jQuery是$('#redButton')

答案 1 :(得分:1)

您应该使用jQuery或基本的JavaScript选择器样式。如果你混淆它们就会发生这种拼写错误。

jQuery样式:

<script type="text/javascript">
    var newestLink = "";
    window.setTimeout(function(){
        var newLink = $('.link:last').attr("href");
        newestLink = newLink;
    }, 1500);

    window.setTimeout(function(){
        alert(newestLink);
        var node = $('#redButton');
        node.click(function() {
            node.attr('href', newestLink);
        });
    }, 3000);
</script>

一个更好的方法,然后使用一些讨厌的超时是在DOM准备好后立即使用ready事件:

<script type="text/javascript">
    $(function(){ // execute this code on ready
        var newLink = $('.link:last').attr('href');
        var node = $('#redButton');
        node.click(function() {
            node.attr('href', newestLink);
        });
    });
</script>

答案 2 :(得分:0)

请在chrome和mozilla中复制n代码以下代码,而不会出现consol错误。

<script type="text/javascript">
var newestLink = "";
window.setTimeout(function(){
var newLink = $('.link:last').attr("href");
newestLink = newLink;
}, 1500);

window.setTimeout(function(){
alert(newestLink);
$("#redButton").click(function(e) {
    $(this).prop("href",newestLink);
});
}, 3000);
</script>
相关问题