在左和右单击事件更改每个输入值

时间:2018-02-25 11:55:41

标签: javascript

左键单击它会提醒值0右键单击它会提醒值2。我想在每个按钮上单击以将输入值更改为以下内容而不是警报:

  

左键单击时,单击的输入应显示值0   
  右键单击单击的输入应显示值1



 function WhichButton(event) {
       var a = event.button;
       if(a === 0 )alert("Button clicked: "+a);//when clicked button value should be 0
       if(a === 2 )alert("Button clicked: "+a);//when clicked button value should be 1
    }

<input type="text" onmousedown="WhichButton(event)" >
<input type="text" onmousedown="WhichButton(event)" >
<input type="text" onmousedown="WhichButton(event)" >
<input type="text" onmousedown="WhichButton(event)" >
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

只需修改WhichButton功能即可更改目标元素的value属性。

编辑:根据评论中的要求,我将onmousedown替换为onmouseup,以便在鼠标事件结束时触发事件。我添加了event.target.blur()以强制失去焦点。最后,我在输入上添加了oncontextmenu="return false;",以防止显示上下文菜单。

function WhichButton(event) {
  var a = event.button;
  if (a === 0) event.target.value = 0;
  if (a === 2) event.target.value = 1;
  event.target.blur();
}
<input type="text" onmouseup="WhichButton(event)" oncontextmenu="return false;">
<input type="text" onmouseup="WhichButton(event)" oncontextmenu="return false;">
<input type="text" onmouseup="WhichButton(event)" oncontextmenu="return false;">
<input type="text" onmouseup="WhichButton(event)" oncontextmenu="return false;">

答案 1 :(得分:0)

右键单击索引2,而不是1

enter image description here

因此,如果您想在右键单击时提醒1,则可以在这种情况下对1进行硬编码,如下所示:

function WhichButton(event) {
  var a = event.button;
  if(a === 0 ) event.target.value = 0;
  if(a === 2 ) event.target.value = 1;
}
<input type="text" onmousedown="WhichButton(event)" >
<input type="text" onmousedown="WhichButton(event)" >
<input type="text" onmousedown="WhichButton(event)" >
<input type="text" onmousedown="WhichButton(event)" >

有关MouseEvent.button的更多信息:https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button