0

无法通过 Chrome 上的 Javacript 控制台在“tr”元素上触发onmouseup事件。

元素是这样的(抱歉,不能分享确切的代码):

< tr class="one" style="height:20px;" onmouseup="click(event,this)"> Text </tr>

在控制台中,我执行了以下步骤:

document.getElementsByClassName("one")[0].onmouseup()

我得到错误:

Uncaught TypeError: Cannot read property 'metaKey' of undefined
    at Object.i [as click] (filename:linenumber)
    at HTMLTableRowElement.onmouseup (Workbox?ajax:1)
    at <anonymous>:1:45

在随附的 js 源文件中,在给定行号的函数 i 中, 正在检查event.metaKey :

    n = b.metaKey || b.ctrlKey

在这一行中,错误显示。

此事件在我自己手动(鼠标)单击时起作用。当我使用该命令执行相同操作时,它无法正常运行。由于这个“元密钥”没有正确传递给它。我可以通过 onmouseup() 调用传递它吗?还有其他方法吗?在 mouseEvents 的上下文中,metakey 到底指的是什么?在其他问题上,据说“Win”键是元键。但是当手动点击时,我不按任何其他键,只按鼠标。它在那里如何运作?

我的最终目标是在同一个元素上调用同一个函数onmouseup,但在 Java 中使用 selenium 库。我还在使用 xpath 获得的元素上使用 JavaScript Executor。它在那里也给出了同样的错误。因此,如果这有效,它也应该在那里有效。

我已仔细检查是否选择了相同的元素而不是其他元素。我能做些什么来解决这个问题?

4

3 回答 3

3

就像@teemu 在评论中所说的那样,您所做的不是事件触发器,而是对函数的调用onmouseup()。问题是这个调用没有b在你的例子中调用的事件参数所以n = b.metaKey || b.ctrlKeyn = undefined.metakey || undefined.ctrlKey

要创建 mouseup 事件,请使用:

newEvt = new MouseEvent("mouseup", {
    气泡:真的,
    可取消:真,
    screenX: <你想要的 X 值>,
    screenY: <你想要的 Y 值>,
    clientX: <你想要的 X 值>,
    clientY: <你想要的 Y 值>
});

// screenX, screenY, clientX 和 clientY 是可选的,默认为 0

document.getElementsByClassName("one")[0].dispatchEvent(newEvt);

请参阅 MDN MouseEvent 文档:https ://developer.mozilla.org/en-US/docs/Web/API/MouseEvent


关于元键,它们对应windows key于 mac 上的 或 ⌘<code>键(来源:https ://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/metaKey )

于 2018-07-31T09:42:40.967 回答
2

通过这种方式,您可以将事件与您需要的数据绑定(以修复错误,或出于任何其他原因) -

var e = new Event('mouseup');
document.getElementsByClassName("one")[0].trigger(e);
于 2018-07-31T09:40:31.360 回答
0

onmouseover 和 onmouseout


< tr class="one" style="height:20px;" onmouseover ="click('first value','2nd value')"> Text </tr>

对于 onmousedown="mouseDown()" onmouseup="mouseUp()"

这是示例

function mouseDown() {
    document.getElementById("myP").style.color = "red";
}

function mouseUp() {
    document.getElementById("myP").style.color = "green";
}
<p id="myP" onmousedown="mouseDown()" onmouseup="mouseUp()">
Click the text! The mouseDown() function is triggered when the mouse button is pressed down over this paragraph, and sets the color of the text to red. The mouseUp() function is triggered when the mouse button is released, and sets the color of the text to green.
</p>

<script>
function mouseDown() {
    document.getElementById("myP").style.color = "red";
}

function mouseUp() {
    document.getElementById("myP").style.color = "green";
}
</script>
于 2018-07-31T09:43:29.617 回答