Can't change the value of href with javascript

霸气de小男生 提交于 2019-12-13 04:32:04

问题


This is the code:

JS:

function f1(){
    document.getElementById('test').href="link2";
};

HTML:

<a href='link1' id='test' onclick='f1();'> Text </a>

The debugger says f1() is not defined. What could it be? The "a" tag is inside a "span" tag, maybe that?

Edit: Sorry for the JQuery thingy I added it to see what happened :P

I forgot to put the linking of the JS file, my bad:

<script type='script' href='javascript.js'> </script>

回答1:


Where did you put f1? onclick find the function in the global scope, if you didn't define the function in global, then it will not be found.

And $(document).getElementById('test').href="link2"; is wrong too,

it should just be document.getElementById('test').href="link2";

Also, if you are using jQuery, then the best way not use the inline onclick:

$(function(){
    $('#test').click(function() {
        $(this).attr('href', 'link2');
    });
});


来源:https://stackoverflow.com/questions/18582803/cant-change-the-value-of-href-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!