drw85135 2019-02-27 00:39
浏览 80

Wordpress - 如何在Javascript变量中获取Post_ID()和echo?

So I basically want to do something unique for every loop. In my loop, I have a button that links to each post. But I also have an onClick event on the button that appends another class.

So basically, if I click a button, it adds a class that turns the button red. Also, I had to put the <script> tag in the loop because otherwise, all buttons on the page turn red since the page displays around 5 loops (posts).

So I'm trying to target just one loop's button. (I hope that makes sense).

So here's an example:

<?php
while (have_posts()) : the_post();
...

<a class="post-<?php the_ID()?> downloadButton" onClick="downloadSuccess();">text</a>


<script>
  function downloadSuccess() {  
var x = document.getElementsByClassName("downloadButton");
var i;
for (i = 0; i < x.length; i++) {
  x[i].classList.add("downloadButton-active"); 
}  
} 
</script>


...
?>

enter image description here

What I want is to target each loop's button using the the_ID() and the static class.

Example:

var x = document.querySelectorAll('.downloadButton,.post-<?php echo the_ID() ?>'); 

But that doesn't work, I guess because you can't echo php inside javascript?

Also, is there a way to not put the javascript inside the loop, yet still target each loop's button based on the_iD()? I would hate to have to put the javascript for every loop just to target the button for each loop.

Can anyone help?

  • 写回答

1条回答 默认 最新

  • doulin9679 2019-02-27 15:40
    关注

    try

    <a href="#" id="<?php the_ID()?>" class="downloadButton">text</a>
    

    move out from loop:

    <script>
      document.addEventListener( 'click', function( event ) {
        event.preventDefault();
        if (!event.target.matches('.downloadButton')) return;
        document.getElementById( event.target.id ).classList.add( "active" );
      }, false);
    </script>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算