我有一个代码:
<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>
很难获得动态生成的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构建页面,则在隐藏的父母元素上使用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>