[英]Multiple onclicks on the same div
I am trying to add a second onclick
function to my element but so far without success, tried with different separators, same quotations and such but it does not work yet. 我正在尝试向我的元素添加第二个
onclick
函数,但到目前为止没有成功,尝试使用不同的分隔符,相同的引号等,但是尚不成功。
This is the code : 这是代码:
<a title="course" onclick="if(document.getElementById('spoiler') .style.display=='none') {document.getElementById('spoiler') .style.display=''}else{document.getElementById('spoiler') .style.display='none'};" onclick="if(document.getElementById('nav-res') .style.display=='block') {document.getElementById('nav-res') .style.display='none'};">Course</a>
Can anyone point out what I am doing wrong ? 谁能指出我做错了什么? Much appreciated
非常感激
You cannot add multiple onclick
statements. 您不能添加多个
onclick
语句。
You need to add a semicolon ( ; ) between the commands. 您需要在命令之间添加分号(;)。
<a href="#" onclick="alert('this is command 1'); alert('this is command 2');">click me</a>
//---------------------------------------------^---------------------------^
However, I would not do it the way you are doing it. 但是,我不会像您那样做。
I would make a separate function that does whatever you are trying to do. 我将创建一个单独的函数来执行您想要执行的任何操作。
It's not good practice to put everything in the html (inline). 将所有内容都放在html(内联)中不是一个好习惯。
I would do it like this: 我会这样做:
<a id="" onclick="clickme()">
<script>
function clickme() {
// action 1
if( document.getElementById('spoiler').style.display=='none' ){
document.getElementById('spoiler').style.display='';
}
else{
document.getElementById('spoiler').style.display='none';
};
// action 2
if( document.getElementById('nav-res').style.display=='block' ){
document.getElementById('nav-res') .style.display='none';
}
}
</script>
I encourage you to try using event listeners: 我鼓励您尝试使用事件侦听器:
<a href='#' id='mytag'>
and then: 接着:
<script>
document.getElementById('mytag').addEventListener("click", function(){
alert(1)
}, false);
document.getElementById('mytag').addEventListener("click", function(){
alert(2)
}, false);
</script>
or with jquery: 或与jQuery:
<script>
$('#mytag').click(function(){ alert(1) })
$('#mytag').click(function(){ alert(2) })
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.