我一直在网上寻找,但没有找到我的问题的直接答案:
你能为标签使用 onClick 吗?
换句话说,你能做到这一点吗(注意通过 php 回显)?
echo "<a href=\"#\" id =\"loginbutton\" onClick=\"counter()\"></a>\n";
我尝试运行它,但是当我点击链接时,我的计数器函数没有被调用。
我的其余代码片段:
echo "<script type=\"text/javascript\" src=\"src\jquery\jquery.js\">\n";
echo "function counter(){\n";
echo "alert(\"HELLO WORLD!\");\n";
echo "}\n";
echo "</script>\n";
echo "<a href=\"#\" id =\"loginbutton\" onClick=\"counter()\"></a>\n";
最佳答案
尽管这应该 有效,但最好不要内联绑定(bind)事件。我建议调查 addEventListener
对于旧版本的 IE,attachEvent
.有关这些的更多信息,请参见此处的主题:Correct usage of addEventListener() / attachEvent()?
如果您等待窗口准备就绪,请确保该元素在页面上并定义为您可以访问它。
window.onload = function(){
//add any event listeners using the above methods in here
}
Example :
<script>
window.onload = function(){
var t = document.getElementById("test");
t.addEventListener("click", sayHi, false);
function sayHi(){
alert("Hi");
}
}
</script>
<div id="test">test</div>
根据你上面的 echo 语句,如果你决定让它那样工作,那么你可以试试这个:
echo "<script type='text/javascript' src='src/jquery/jquery.js'></script>\n";
echo "<script>\n"
echo "function counter(){\n";
echo "alert('HELLO WORLD!');\n";
echo "}\n";
echo "</script>\n";
echo "<a href='#' id ='loginbutton' onClick='counter()'></a>\n";
请注意,我关闭了包含 jQuery 的脚本标签,并在其正下方添加了一个新的开始标签。
编辑:
Script tags that reference external resources (via the src attribute) are no longer able to execute script embedded within the tag itself.
阅读更多 here
关于php - 通过在超链接中使用 onClick 调用 javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13290672/