【问题标题】:How to make this div clickable?如何使这个 div 可点击?
【发布时间】:2015-12-28 04:17:53
【问题描述】:

我想让这个 wordpress 插件的每个“卡片”都可以点击 (http://www.davidbo.dreamhosters.com/?page_id=11)

所以我添加了一个 Pure JS 元素,代码如下:

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

它不工作,所以我想知道这是多么错误。

谢谢!

【问题讨论】:

    标签: javascript css


    【解决方案1】:

    如果您想为所有卡片应用点击事件处理程序:

    // 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
        }); 
    
    });
    

    【讨论】:

    • 虽然这会产生 OP 正在寻找的结果,但我相信 OP 将无法遵循这个答案。你应该分解每个部分的作用。
    • 你是对的。我添加了一些可能有帮助的 cmets。如果代码需要更多说明,请告诉我。
    • 你如何获得 addEventListener 中的盒子标识,比如数字(第一个盒子,第二个盒子)?
    • index变量表示cards数组中被点击的卡片的编号。
    【解决方案2】:

    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
    

    【讨论】:

    • 我在 alert('It works!' + i) 中添加了 'i' 变量的代码值,但 'i' 变量总是获取找到的 div 类的数量。我怎样才能准确地得到它点击的盒子号码
    • 那是因为这是 i 在循环结束时的最终数字。
    • 这可能会有所帮助:stackoverflow.com/questions/8801787/…
    猜你喜欢
    • 1970-01-01
    • 2013-09-20
    • 1970-01-01
    • 1970-01-01
    • 2016-04-25
    • 1970-01-01
    • 2010-11-01
    相关资源
    最近更新 更多