简体   繁体   English

多个元素同时使用同一单击功能。 怎么样?

[英]Multiple elements using the same click function at once. How?

I am using Raphael JS, but I think this is pure JavaScript or maybe jQuery question. 我正在使用Raphael JS,但我认为这是纯JavaScript或jQuery问题。

I have two elements a text and an circle(ellipse) and I am using a variable to store them for later usage. 我有两个元素,一个文本和一个圆(椭圆),我正在使用一个变量来存储它们,以备后用。

So, I was thinking that instead of repeating myself over and over again I will create an array and use it on click. 因此,我在想,不是要一遍又一遍地重复自己,而是要创建一个数组并在单击时使用它。

But it is not working. 但这是行不通的。 How to solve this problem and assign onclick for every variable(object) in my array? 如何解决此问题并为数组中的每个变量(对象)分配onclick?

var circle = paper.ellipse(350, 320, 95, 90);
var text = paper.text(350, 320, "My text");

var myArray = [circle, text];
myArray.click(function () {
    window.location = "http://somewebsite.com";
});

The jQuery $.each function can help you with this; jQuery $ .each函数可以帮助您;

$.each(myArray, function(i, v) {
    v.click(function() {
        window.location = "http://somewebsite.com";
    });
});

You needn't store the objects in an array if you just want to keep them around, you've already referenced them with two variables: circle and text . 如果只想保留对象,则不必将它们存储在数组中,您已经使用两个变量来引用它们: circletext Define the function once and then assign it to any element that uses it: 定义函数一次,然后将其分配给使用该函数的任何元素:

var circle = paper.ellipse(350, 320, 95, 90);
var text = paper.text(350, 320, "My text");

function clickFunction()
{
    window.location = "http://somewebsite.com";
}

circle.addEventListener("click", clickFunction);
text.addEventListener("click", clickFunction);

Or, using jQuery: 或者,使用jQuery:

circle.click(clickFunction);
text.click(clickFunction);

If you want to do it with raphaelJS ... 如果您想使用raphaelJS来做...

var circle = paper.ellipse(350, 320, 95, 90);
var text = paper.text(350, 320, "My text");
var click_set = paper.set();
click_set.push(circle);
click_set.push(text);

click_set.click(function(){
 // do what you want ... this function will automatically be bound to all the elements that //you push in the set
               });

Just loop over the elements and append the handler to each of them. 只需循环遍历元素,然后将处理程序附加到每个元素即可。 No need for any libraries. 无需任何库。

var circle = paper.ellipse(350, 320, 95, 90);
var text = paper.text(350, 320, "My text");

var myArray = [circle, text];
var handler = function () {
    window.location = "http://somewebsite.com";
};

for (var i = 0; i < myArray.length; i++) {
    myArray[i].onclick = handler;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM