将元素的DOM位置存储在变量中?

将元素的DOM位置存储在变量中?

问题描述:

I want the variable $slideNumber to get the number of the <input> element depending on what position it is in the DOM. So if it's the first child, it would get 1, the second child would get 2, etc.

The output would look something like this:

<div>
    <input type="radio" name="slider" id="slide1">
    <input type="radio" name="slider" id="slide2">
    <input type="radio" name="slider" id="slide3">
    <input type="radio" name="slider" id="slide4">
    ...
</div>

Here is the code:

<?php if( have_rows('slides') ):
    while ( have_rows('slides') ) : the_row();

    $slideNumber = // not sure what to do here

    ?>

<input type="radio" name="slider" id="slide<?php echo $slideNumber; ?>">

<?php endwhile;endif; ?>

Simply initialise your variable before the loop and increment it on every iteration.

<?php 
if( have_rows('slides') ):
    $slideNumber = 1;
    while ( have_rows('slides') ) : the_row();
?>

<input type="radio" name="slider" id="slide<?php echo $slideNumber++; ?>">

<?php endwhile;endif; ?>

The have_rows in if and while are redundant:

<?php 
for( $slideNumber = 1; have_rows('slides'); $slideNumber++ ):
    the_row();
    echo '<input type="radio" name="slider" id="slide' . $slideNumber . '">';
endfor;
?>