-1

我已经在myform.php具有单选组输入类型的模板上创建了表单,并且值更新为onchange="javascript:document.post.submit()"';. 因此,每当我更改选择时,值都会随着页面刷新而更新。有什么方法可以让我在不使用 ajax 刷新页面的情况下更新我的选择?

     <?php
          $foods = array('pasta', 'burger', 'pizza','popcorn');


            foreach ($foods as $food) {
            echo  '<input name="my_favorite_food" type="radio"   onchange="javascript:document.post.submit()"';
            $option = 'id=" ' .$food . '"';
            $option = 'value="' . $food . '"';

            if ($food == $my_favorite_food) $option .= 'checked="checked"';
            $option .= '>';
            $option .= '<label for=" '.$food .' ">' . $food .'  ';
            $option .=  '</label>';
            echo $option;
              }
         ?>

       <div id ="block">
        <?php 

        if ($my_favorite_food == "pasta") : ?>

          <h2>your favorite food is pasta</h2>
           <p> my pasta recipe......   </p>

        <?php endif;?>

        if ($my_favorite_food == "burger") : ?>

          <h2>your favorite food is burger</h2>
           <p> my burger recipe......   </p>

        <?php endif;?>

        if ($my_favorite_food == "pizza") : ?>

          <h2>your favorite food is pizza</h2>
           <p> my pizza recipe......   </p>

        <?php endif;?>

        if ($my_favorite_food == "popcorn") : ?>

          <h2>your favorite food is popcorn</h2>
           <p> my popcorn recipe......   </p>

        <?php endif;?>
<div>
4

1 回答 1

2

为所有选项生成 HTML,并有条件地隐藏 ( style="display:none") 当前未选中的选项。(生成的)HTML 看起来像这样:

<input type="radio" value="burger" name="favourite_food" class="favourite"/> Burger
<input type="radio" value="popcorn" name="favourite_food" class="favourite"/> Popcorn
...

<div id="burger" class="favourite-display">
    <h2>your favorite food is burger</h2>
    <p> my burger recipe...</p>
</div>
...

然后是 jQuery:

$(document).ready(function() {
    $('.favourite').on('change', function(event) {
        $('.favourite-display').hide();
        $('#' + this.value).show();
    });
});

不需要每次都实际提交表单(使用或不使用 AJAX)来控制显示的部分。

于 2013-03-25T11:20:20.930 回答