我试过了:
var clickEvent = document.createEvent('MouseEvents');
clickEvent.initEvent("mousedown", true, true);
jQuery('.left-rail-facets .facet-list .facet.CS .suggestion[data-value="B"] a')[0].dispatchEvent(clickEvent);
但它无法触发网站上的操作。 没有错误返回。
答案 0 :(得分:4)
这是您使用" mousedown"以编程方式触发对DOM元素的点击的方式。事件。要回答您的问题,您需要在源代码中包含两件事:
事件侦听器检测点击次数
和
jQuery行中多个选择器之间的逗号。
请运行下面的代码段,其中显示修改后的jQuery行和正确运行的侦听器。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
// You must have event listeners to see if anything is actually happening. For example, here I will add only a listener to the first element:
jQuery(".left-rail-facets")[0].addEventListener('mousedown', function(e) {
jQuery(".left-rail-facets")[0].innerHTML = "I have received a click.";
}, false);
// Now here is the code from your question. Please see how I have commas instead of spaces in my jQuery selector:
var clickEvent = document.createEvent('MouseEvents');
clickEvent.initEvent('mousedown', true, true);
jQuery('.left-rail-facets,.facet-list,.facet.CS,.suggestion[data-value="B"],a')[0].dispatchEvent(clickEvent);
});
</script>
</head>
<body>
<h1>I am a Webpage</h1>
<p class="left-rail-facets">I have not received a click.</p>
<p class="facet-list">I have not received a click.</p>
<facet class="CS">I have not received a click.</facet>
<p class="suggestion" data-value="B">I have not received a click.</p>
<a href="url">I have not received a click.</a>
</body>
</html>
&#13;
答案 1 :(得分:1)
您需要使用document.createEvent和event.initMouseEvent:
var element = document.querySelector('.left-rail-facets .facet-list .facet.CS .suggestion[data-value="B"] a');
//or var element = jQuery('.left-rail-facets .facet-list .facet.CS .suggestion[data-value="B"] a')[0];
var elementRect = element.getBoundingClientRect();
var mouseEvent = document.createEvent('MouseEvents');
mouseEvent.initMouseEvent('mousedown', true, true, window, 0, elementRect.left, elementRect.top);