向每个数组项添加点击

时间:2019-06-07 07:08:36

标签: javascript jquery tampermonkey

所以我的问题是,我希望脚本在将每个类简单地记录在控制台后单击它。

我尝试在几段代码之后添加一些.click()方法,但是没有运气。

这是下面的代码

var array = ['.button.color.color-41d841', '.button.color.color-dc0000', '.button.color.color-1e00e9', '.button.color.color-ff6f00'];
var interval = 1000; // how much time should the delay between two iterations be (in milliseconds)?
array.forEach(function(el, index) {
  setTimeout(function() {
    console.log(el);
  }, index * interval);
});
console.log('Loop finished.');

它只是打印元素的类。

已解决

var array = ['.button.color.color-41d841', '.button.color.color-dc0000', '.button.color.color-1e00e9', '.button.color.color-ff6f00'];
var interval = 1000; // how much time should the delay between two iterations be (in milliseconds)?
array.forEach(function(el, index) {
  setTimeout(function() {
    console.log(el);
    $(el).click()
  }, index * interval);
});
console.log('Loop finished.');

2 个答案:

答案 0 :(得分:0)

您需要调用以下脚本。

  

$(document).on('click',el,function(){});

因为您是动态绑定点击事件

 var array = ['.label-key', '.button.color.color-dc0000', '.button.color.color-1e00e9', '.button.color.color-ff6f00'];
var interval = 1000; // how much time should the delay between two iterations be (in milliseconds)?
array.forEach(function (el, index) {
$(document).on('click',el,function(){}); 
setTimeout(function () {
console.log(el);
}, index * interval);
});
console.log('Loop finished.');

答案 1 :(得分:-1)

尝试此操作,您需要找到元素并单击它

var array = ['.button.color.color-41d841', '.button.color.color-dc0000', '.button.color.color-1e00e9', '.button.color.color-ff6f00'];
var interval = 1000; // how much time should the delay between two iterations be (in milliseconds)?
array.forEach(function (el, index) {
setTimeout(function () {
console.log(el);
document.querySelector(el).click()
}, index * interval);
});
相关问题