【问题标题】:Wordpress: Get ID from wp_query post for jqueryWordpress:从 jquery 的 wp_query 帖子中获取 ID
【发布时间】:2019-02-14 14:42:01
【问题描述】:

我有一个代码:

<div id="parent-<?php the_ID(); ?>" class="first">

我想在 JQuery 中使用它来实现点击功能,例如:

$('#parent-**??**').click(function (){

我应该如何进行?

【问题讨论】:

  • 您将无法猜测动态 ID。

标签: jquery wordpress parentid


【解决方案1】:

尝试将值从 PHP 传递给 JS:

PHP:

echo sprintf("<script> var theID = %d;</script>", the_ID());
<div id="parent-<?php the_ID(); ?>" class="first">

JS:

 <script>
   alert("current post id = "+theID);
 </script>

更新:

如果您在循环中打印帖子,您可能希望将所有 id 推送到一个数组中。

PHP:

<?php
$posts = [];
if ( have_posts() ) {
    while ( have_posts() ) {
        the_post(); 
        ?>
        <div id="parent-<?php the_ID(); ?>" class="first">
        //
        // Post Content here
        //
        </div>
        <?php
        posts[] = get_the_ID();
    } 
}

echo sprintf("<script> var thePostIDs = %s;</script>", json_encode(posts));

JS:

<script>
    thePostIDs.map(function(id){
     // do something with the id
     $('#parent-'+id).click(function (){
       // do something
     });
    });
</script>

【讨论】:

  • 它不适合我。当我使用&lt;div id="parent-&lt;?php echo sprintf("&lt;script&gt; var theID = %d;&lt;/script&gt;", the_ID()); ?&gt;" class="first"&gt; 并将脚本获取到 JS 时...
  • 混合 PHP + JS 总是一个坏主意.. 最好使用 data-* 标签
  • 能否请您更新您的帖子并显示您的实际代码?很难猜出你的代码到底为什么不起作用
  • 埃里克,抱歉耽搁了。我不知道问题出在哪里,但我只是找到了没有 jquery 的解决方案。无论如何,感谢您的帮助和时间...
  • @admiva 您应该发布您的答案并将其标记为已接受 - 不要接受不能解决您的问题的答案(虽然,它看起来确实是一个好的答案 - 不过,发布要好得多你的发现)
【解决方案2】:

很难获得动态生成的 DOM 属性。 jQuery,虽然它可以使用 AJAX 获取值,但这样做有点开销。 IMO 最好的办法是简单地将 ID 分配给具有通用类的隐藏元素。然后,在您的 jQuery 中,您可以使用泛型类获取动态值并将其附加到 jQuery 选择器以获取动态元素。

如果您可以更改 HTML,您可以这样做:

<div id="hidden-parent" data-id="<?php the_ID(); ?>"></div>

<div id="parent-<?php the_ID(); ?>" class="first">
    <!-- etc. -->
</div>

然后在你的 jQuery 中:

let id = $('#hidden-parent').attr('data-id'),
    parentDiv = $('#parent-'+ id);

parentDiv.click(function()
{
    //whatever
})

这里我们只获取data-id 值并使用它来获取父级-* div

对此有一点需要注意。如果您正在循环 div 来构建页面,那么在 hidden-parent 元素上使用 ID 将不起作用。您可以做的是附加密钥,例如

<?php foreach ($elements as $key => $el) : ?>
    <div id="foo-<?php echo $key; ?>">
        <!-- etc. -->
    </div>
<?php endforeach; ?>

然后在你的 jQuery 中使用 $('#foo-1') 等。

【讨论】:

  • 投反对票,发表评论,以便我更好地回答:)
【解决方案3】:
<div id="parent-<?php the_ID(); ?>" class="first parent" data-id="<?php the_ID(); ?>">
<script>
    $('.parent').click(function (){
         var parentId = $(this).attr('data-id');
        if (parentId != undefined && parentId != '') {
            // do something
        }

     });
</script>

【讨论】:

  • 只有代码的答案不是 IMO 的答案 - 它应该包括对问题和解决方案的解释。
  • IMO人在这里寻找答案,如果他们想学习一些东西,他们可以自己研究和解决
  • 如果这是你的态度,那么,不要回答,因为他们不会从代码中学到任何东西
猜你喜欢
  • 2010-12-04
  • 1970-01-01
  • 1970-01-01
  • 2011-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-12
  • 1970-01-01
相关资源
最近更新 更多