简体   繁体   中英

How do i make buttons generated with php work?

Btn1 fires the getId function appropriately but the other two btns do not, how can i make them work correctly? I think the code below shows what i am trying to achieve so please ignore the rest of this paragraph. This is here because the page will not allow me to post the question until i add more details.

<?php 
    $id ="22";
    $name = "Joseph";
    $btn1 = "<button onclick='getId($id)'>$name $id</button>";
    $btn2 = "<button onclick='getId($id,$name)'>$name $id</button>";    
    $btn3 = "<button onclick='getId($name)'>$name $id</button>";

    echo $btn1;
    echo "<br>";
    echo $btn2; 
    echo "<br>";
    echo $btn3; 
?>

<!DOCTYPE html>
<html>
<script>
    function getId(x, y) {  
        alert(x);
        alert(y)
        console.log(x);
        console.log(y);
    }
</script>
<body>
    "ReferenceError: Joseph is not defined"
</body>
</html>

With regards to passing strings as parameters to a function ( as above ) the string value needs to be quoted otherwise you will get an error. Rather than hardcoding the parameters in this instance what you could do would be to use the arguments object inherent to functions and access the parameters dynamically.

<!DOCTYPE html>
<html>
    <head>
        <title>function arguments and quotes....</title>
    </head>
    <script>
        function getId() {  
            for( let i=0; i < arguments.length;i++ ){
                alert(arguments[i]);
                console.info(arguments[i]);
            }
        }
    </script>
    <body>
        <?php 

            $id ="22";
            $name = "Joseph";
            $btn1 = "<button onclick='getId($id)'>$name $id</button>";
            $btn2 = "<button onclick='getId($id,\"$name\")'>$name $id</button>";    
            $btn3 = "<button onclick='getId(\"$name\")'>$name $id</button>";

            echo $btn1;
            echo "<br>";
            echo $btn2; 
            echo "<br>";
            echo $btn3; 
        ?>  
    </body>
</html>

 function getId() { for( let i=0; i < arguments.length;i++ ){ alert(arguments[i]); console.info(arguments[i]); } }
 <button onclick='getId(22)'>Joseph 22</button><br> <button onclick='getId(22,"Joseph")'>Joseph 22</button><br> <button onclick='getId("Joseph")'>Joseph 22</button>

<?php 
    $id ="22";
    $name = "Joseph";
    $btn1 = "<button onclick='getId($id,\"$name\")'>$name $id</button>";

    echo $btn1;
    echo "<br>";    
?>

<!DOCTYPE html>
<html>
<script>
    function getId(x, y) {  
        alert(x);
        alert(y)
        console.log(x);
        console.log(y);
    }
</script>
<body>
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM