触发鼠标松开事件的编程方法

3

我想编程触发一个mouseup事件,具体如下:

<div id="abc">Click me</div>

<script>
    document.getElementById('abc').addEventListener('mouseup', function () {
        alert('mouseup');
    });
</script>

现在,为了触发,我尝试了以下操作:

document.getElementById('abc').onmouseup();

或者使用jQuery。
$('#x').trigger('mouseup');

这些操作都没有触发alert,所以我在这里一定做错了什么。

演示

更新:使用addEventListener修复了类型错误。


1
document.getElementById('abc').addEventListener('mouseup', function () { alert('mouseup'); });看起来你忘记在getElementById函数中添加id参数了。在这里检查 - undefined
在你贴上的代码中,你要定位的元素的id缺失了。另外,在你的演示中,你调用了一个'onmouseup'方法,但没有传递任何回调函数。如果你查看控制台,你会看到一个错误。尽管在你的演示中,没有那行代码也能正常工作。 - undefined
2个回答

3
点击这里
在此处缺少参数,即getElementById('abc')
document.getElementById('abc').onmouseup();
onmouseup()不是一个函数,而是一个事件属性,应该在某个元素上调用。 $('#x').trigger('mouseup');
应该这样做: $( "#abc" ).click(function() { $( "#x" ).mouseup(); });

3
在下面的代码中,getElementById 没有调用和参数。
document.getElementById.addEventListener('mouseup', function () {
    alert('mouseup');
});

正确的例子

document.getElementById("the id of the element").addEventListener('mouseup', function () {
    alert('mouseup');
});

如果你想通过代码而不是鼠标触发事件,那么在这个链接中已经有了答案如何在JavaScript中触发事件?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接