jQuery-for.each调用包含方法.on的函数

jQuery - for .each call function which contains method .on

本文关键字:on 函数 方法 包含 each 调用 jQuery-for      更新时间:2023-09-26

我需要使用".each"元素jquery方法".on",但我做得不对。。有人能帮忙吗?

从SVG中获取ID并将其放入一个数组:

    var svgZi10 = document.getElementById("svg"); //get the main SVG container
    var svgElementZi10 = svgZi10.contentDocument; //get the inner DOM from SVG
var lock    = []; //new Array
lock[0] = svgElementZi10.getElementById("lock-door-open-right-contour"); //get the inner element by id
lock[1] =  svgElementZi10.getElementById("lock-door-open-left-contour"); //get the inner element by id
lock[2] = svgElementZi10.getElementById("lock-door-closed-right-contour"); //get the inner element by id
lock[3] = svgElementZi10.getElementById("lock-door-closed-left-contour"); //get the inner element by id

使用数组中的对象进行操作(不起作用):

 $.each(lock, function(i,element) {
        $(element).on("mousedown",function(){tab12[0].click() })  
    });

每个对象何时单独(工作):

 var lock1 = svgElementZi10.getElementById("lock-door-open-right-contour"); //get the inner element by id
 var lock2 = svgElementZi10.getElementById("lock-door-open-left-contour"); //get the inner element by id
lock1.addEventListener("mousedown",function(){tab7[0].click()});
lock2.addEventListener("mousedown",function(){tab7[0].click()});

您应该在当前元素上调用.on(),而不是数组:

$.each(lock, function(i,element) {
    $(element).on("mousedown",function(){tab12[0].click() })  
});

如果lock是DOM元素的数组,则不需要.each。当您给jQuery()一个元素数组时,它将创建一个封装它们的jQuery对象。所以你可以写:

$(lock).on("mousedown", function() {
    tab12[0].click();
});

在jQuery集合上使用绑定函数时,它会绑定集合中的所有元素。