简体   繁体   中英

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.

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?

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;

$.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 . 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:

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

If you want to do it with 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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