我想让这个wordpress插件的每张“卡片”都可点击(http://www.davidbo.dreamhosters.com/?page_id=11)
所以我添加了一个带有以下代码的Pure JS元素:
document.getElementsByClassName('fc_card-container').onclick = function() {alert('It works!');}
它没有用,所以我想知道这是多么的错误。
谢谢!
答案 0 :(得分:4)
如果您想为所有卡片应用点击事件处理程序:
// 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
});
});
答案 1 :(得分:0)
document.getElementsByClassName
返回匹配元素的数组。在您的情况下,是一个类名为fc_card-container
的元素数组。下一步是迭代元素并为每个元素分配一个事件监听器,或者使用索引选择一个特定的监听器(从0开始)。
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!');};
};
var cards = document.getElementsByClassName('fc_card-container');
cards[2].onclick = function() {alert('It works!');}; //0,1,2