简体   繁体   中英

How to make this div clickable?

I wanto to make each "card" of this wordpress plugin clickable ( http://www.davidbo.dreamhosters.com/?page_id=11 )

So I added a Pure JS element with the following code:

document.getElementsByClassName('fc_card-container').onclick = function() {alert('It works!');}

and it is not working so I wonder how wrong this is.

Thanks !

If you want to apply a click event handler for all the cards:

// Get all the elements with a .fc_card-container class and store them on a variable
// .getElementsByClassName returns an array-like object with all the selected elements 
var cards = document.getElementsByClassName('fc_card-container');

// Use [].slice.apply(cards) to convert the cards NodeList into an array
// Iterate over the cards array with a .forEach

[].slice.apply(cards).forEach(function(card, index){ 

    // Each array element corresponds to a card element
    // Use the .addEventListener( EVENT, callback ) to attach an event handler for each card element

    card.addEventListener("click", function(e){ 
        alert(); 
        console.log(cards[index]); // Index gives us the exact array position (index) of the clicked card. 
        console.log(e.target); // e.target gives us access to the clicked element
    }); 

});

document.getElementsByClassName returns an array of matched elements. In your case, an array of elements with the class name of fc_card-container . Your next step would be to iterate over the elements and assign an event listener to each or select a specific one using an index (starting with 0).

Assign a click to all

var cards = document.getElementsByClassName('fc_card-container');
for(var i = 0; i < cards.length; i++){ //iterate through each card
   cards[i].onclick = function() {alert('It works!');};
};

Assign a click to a single card (eg: 3rd card)

var cards = document.getElementsByClassName('fc_card-container');
cards[2].onclick = function() {alert('It works!');}; //0,1,2

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