问题描述
这是代码:
JS:
function f1(){
document.getElementById('test').href="link2";
};
HTML:
<a href='link1' id='test' onclick='f1();'> Text </a>
调试器说未定义f1().会是什么呢? "a"标签位于"span"标签内,也许是这样吗?
The debugger says f1() is not defined. What could it be? The "a" tag is inside a "span" tag, maybe that?
很抱歉,我添加了JQuery,以查看发生了什么事情:P
Sorry for the JQuery thingy I added it to see what happened :P
我忘记了链接JS文件,这很糟糕:
I forgot to put the linking of the JS file, my bad:
<script type='script' href='javascript.js'> </script>
推荐答案
您将f1
放在哪里? onclick
在全局范围内查找该函数,如果您未在全局范围内定义该函数,则将找不到该函数.
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.
$(document).getElementById('test').href="link2";
也是错误的,
应该只是document.getElementById('test').href="link2";
此外,如果您使用的是jQuery,则最好的方法是不使用内联onclick
:
Also, if you are using jQuery, then the best way not use the inline onclick
:
$(function(){
$('#test').click(function() {
$(this).attr('href', 'link2');
});
});
这篇关于无法使用javascript更改href的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!