首页 > 解决方案 > 如何使用ajax检测哪个按钮被按下

问题描述

我希望每次按下“plato”按钮时(有几个,因为我在循环中创建它们)执行此函数“ $ ('# plato'). click (function ()”但我观察到此代码仅在按下第一个按钮时执行。对于其他人,它不会被执行。

菜单.php:

<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="estilos.css">
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="ajax.js"></script>
</head>
<body>
    <?php
    $restaurante=$_GET['restaurante'];
    chdir(getcwd()."/".$restaurante);
    $id_fichero= @fopen("menus.txt","r") or die("<B>El fichero no se pudo abrir");
    ?>
    <?php
        while (!feof($id_fichero))
        {            
        if(($linea=trim(fgets($id_fichero,256),"\n\r"))!=false) 
        {
            echo("<button type='button' class='accordion'>".$linea."</button>");                
            echo("<div class='panel'>");
            $id_fichero2= @fopen($linea.".txt","r") or die("<B>El fichero no se pudo abrir");
            while (!feof($id_fichero2))
            {                   
                if(($linea2=trim(fgets($id_fichero2,256),"\n\r"))!=false)
                {
                    echo("<button type='button' id='plato' name='plato'>".$linea2."</button><br>");
                    echo("<input type='hidden' id='nombrePlato' name='nombrePlato' value='".$linea2."'>");
                }
            }
            echo ("</div>");
        }
        }
        
    ?>
    <div id="carrito">
        
    </div>
<script src="collapsible.js"></script>

</body>
</html>

ajax.js

$(document).on('ready',function(){  
    $('#plato').click(function(){
    alert("I'm here");   
    var url = "anadirCarrito.php";
    $.ajax({                        
       type: "POST",                 
       url: url,                     
       data: $('#platos').serialize(), 
       success: function(data)             
       { 
         $('#carrito').html(data);  
        
       }
       });
    });
});

标签: ajax

解决方案


推荐阅读