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>
    
    评论

报告相同问题?

悬赏问题

  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了