问题
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