【发布时间】:2019-02-14 14:42:01
【问题描述】:
我有一个代码:
<div id="parent-<?php the_ID(); ?>" class="first">
我想在 JQuery 中使用它来实现点击功能,例如:
$('#parent-**??**').click(function (){
我应该如何进行?
【问题讨论】:
-
您将无法猜测动态 ID。
我有一个代码:
<div id="parent-<?php the_ID(); ?>" class="first">
我想在 JQuery 中使用它来实现点击功能,例如:
$('#parent-**??**').click(function (){
我应该如何进行?
【问题讨论】:
尝试将值从 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>
【讨论】:
<div id="parent-<?php echo sprintf("<script> var theID = %d;</script>", the_ID()); ?>" class="first"> 并将脚本获取到 JS 时...
很难获得动态生成的 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') 等。
【讨论】:
<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>
【讨论】: