【问题标题】:Custom Javascript not working in Wordpress自定义 Javascript 在 Wordpress 中不起作用
【发布时间】:2020-12-04 11:04:22
【问题描述】:

我的目的是为网格内的每个投资组合卡片添加摘录(目前,这些仅显示图像、标题和类别)。

我找到了一种将摘录插入卡片并遍历所有卡片的方法,但即使循环按预期工作(记录每次迭代),摘录也不会插入所有卡片。如果我指定了 targetsArray 的特定索引,摘录只会插入一张卡片。我将此行注释掉以供参考。

window.onload = function() {
    let targets = document.querySelectorAll('.entry-title');
    let newElem = document.createElement('p');
    let excerpt = 'This will be the excerpt...';
    newElem.innerHTML = excerpt;
    
    let targetsArray = [];
    
    for (let i = 0; i < targets.length; i++) {
      targetsArray.push(targets[i]);
    }
    
    targetsArray.forEach(target => {
      console.log(target);
      target.parentNode.insertBefore(newElem, target.nextSibling);
    });
    // targetsArray[1].parentNode.insertBefore(newElem, targetsArray[1].nextSibling);
    
  };

注意:如果您想知道为什么我没有使用更简单的方法将节点列表转换为数组,那是因为它们不起作用。

我试过了

const targets = [...document.querySelectorAll(".entry-title")];

还有……

Array.from(targets)

作为参考,这是我尝试进行这些更改的页面 equipourkids.org

【问题讨论】:

    标签: javascript arrays wordpress foreach


    【解决方案1】:

    我不知道您是否出于特定原因尝试使用纯 JS 执行此操作,但 Wordpress 默认情况下已经加载了 jQuery(如果您没有删除它),并且使用 jQuery 执行此操作应该比那更简单.

    let targets = $('.entry-title');
    let newElem = $('<p>This will be the excerpt...</p>')
            
    targets.each(function (idx, item){
        $(item).parent().insertBefore(newElem);
    });
    

    我只是不明白你想根据你的 HTML 结构在哪里插入这些例外。应该在 entry-info 里面还是什么?

    【讨论】:

    • 谢谢,我不知道。摘录应该在入口标题内。我刚刚尝试了您的代码并收到此错误: Uncaught TypeError: $ is not a function 。也许是因为他们使用的 Phlox 主题?
    • Argh 抱歉,您需要使用 jQuery 而不是 $。只需将“$”替换为“jQuery”就可以了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 2016-06-18
    • 2015-11-08
    • 2017-09-08
    • 2014-03-26
    相关资源
    最近更新 更多