触发函数onclick()传递被点击元素的id

时间:2014-10-23 18:08:15

标签: javascript html onclick right-click

我有一张桌子,其中每个td都是这样的:

<td onclick="GetCellValues(this.id)" id="myrowID">My text</td>

我需要的Javascript函数是这样的:

function GetCellValues(clicked_element_ID) {
   if (RIGHTCLICK){
      document.getElementById(clicked_element_ID).style.backgroundColor="red";
      THEN CALL FUNCION1();
   }
   else if(LEFTCLICK OR WHEELCLICK){
      document.getElementById(clicked_element_ID).style.backgroundColor="green";
      THEN CALL FUNCION2();
   }
}

所以问题是:如何按下LEFT,RIGHT或WHEEL鼠标按钮怎么识别?

提前感谢您的帮助!!!

2 个答案:

答案 0 :(得分:0)

您可以这样做:

<script>

    function mouseHandler(event) {
        if( event.button == 2){
            this.style.backgroundColor = "red";
            rightFunc();
        } else{
            this.style.backgroundColor = "blue";   
            otherFunc();
        }
    }

    function rightFunc(){ alert("rightclick");}
    function otherFunc(){ alert("left or wheel");}

    window.onload = function(){
        document.getElementById("myrowID").addEventListener("mousedown", mouseHandler);
    }
</script>

请在此处查看:JSFiddle

答案 1 :(得分:-1)

如果你想使用jQuery,请执行以下操作:

$('#myrowID').mousedown(function(event) {
    switch (event.which) {
        case 1:
            //left
        case 2:
            //middle
            document.getElementById(clicked_element_ID).style.backgroundColor="green";
            //THEN CALL FUNCION2();
            break;
        case 3:
            //right
            document.getElementById(clicked_element_ID).style.backgroundColor="red";
            //THEN CALL FUNCION1();
            break;
        default:
            alert('I don't know what button that was!');
    }
});

注意:您需要导入jquery,因此请添加:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>