-1

我正在尝试将 onclick 方法添加到链接。

我想在用户单击链接 A 时制作 a++,而当用户单击链接 B 时,无论a值是什么,我都想制作 a++。

我的代码:

JS

var a=0;

function swapPost(a){

 //I want to make a++ when user click linkA;
 //a-- when user click linkB
 //not sure how to do this

   if(a>10){
    a=0;
   }
    if(a<0){
    a=0;
   }

}

swapPost(a);

html

<a href="#" onclick="swapPost(a)">LinkA</a>
<a href="#" onclick="swapPost(a)">LinkB</a>

我想知道是否有人可以帮助我解决这个问题。非常感谢。

4

3 回答 3

2

与其a作为参数传入,不如通过其 id(您尚未定义)传入被点击的链接。传入this函数。

<a id='linka' href="#" onclick='swapPost(this)'>LinkA</a>
<a id='linkb' href="#" onclick='swapPost(this)'>LinkB</a>

var a=0;    
function swapPost(nodeClicked){
   // Check the id of the node passed to the function.
   if (nodeClicked.id == 'linka') {
     a++;
   }
   else if (nodeClicked.id == 'linkb') {
     a--;
   }
   else return;

   // Set to zero if outside your bounds
   if(a>10){
    a=0;
   }
    if(a<0){
    a=0;
   }
}

在这里,它正在运行,登录到控制台......

通常,将函数绑定到事件而不是将它们内联到属性中是更好的做法。因为this里面的 anonclick指的是被点击的节点,所以你实际上不需要将它作为参数传入。然后,您可以绑定 onclick 事件而无需内联,并this在内部调用。

<a id='linka' href="#">LinkA</a>
<a id='linkb' href="#">LinkB</a>

var a=0;    
var swapPost = function(){
   // Check the id of the node passed to the function.
   if (this.id == 'linka') {
     a++;
   }
   else if (this.id == 'linkb') {
     a--;
   }
   else return;

   // Set to zero if outside your bounds
   if(a>10){
    a=0;
   }
    if(a<0){
    a=0;
   }
}
// Bind the function to the links
document.getElementById('linka').onclick = swapPost;
document.getElementById('linkb').onclick = swapPost;

这是更新的版本

于 2012-07-06T02:50:12.347 回答
1
<a href="#" id="a">LinkA</a>
<a href="#" id="b">LinkB</a>​

JS

<script type="text/javascript">
window.onload=function(){
    var a=0;
    var els=document.getElementsByTagName('a');
    for(i=0;i<els.length;i++)
    {
        (function(i){
            els[i].onclick=function(){
                if(this.id=='a') a++;
                else a--;
                a = a < 0 ? 0 : (a > 10 ? 0 : a);
                return false;
            }
        })(i);
    }
}
</script>

演示。

于 2012-07-06T02:47:52.737 回答
0

试试这个: Javascript:

var a=0;
function swapPost(val){
  a=a+val;
 }

HTML:

  <a href="#" onclick='javascript:return swapPost(1);'>LinkA</a>
  <a href="#" onclick='javascript:return swapPost(-1);'>LinkB</a>
于 2012-07-06T02:54:37.053 回答