php onclick函数“”和“”不起作用

php onclick函数“”和“”不起作用

问题描述:

i have an question. How can i make this work?

normal html (works):

<button class="btn" onclick="myFunction('pd')">PD</button>

under php does not work!:

Version1: echo '<button class="btn" onclick="myFunction('pd')">PD</button>';
Version2: echo '<button class="btn" onclick="myFunction("pd")">PD</button>';

how did i have to change this? ty guys

1st thx for so many necessary answers! perfect and short answer was from Mark in the 2nd answer!

echo '<button class="btn" onclick="myFunction(\'pd\')">PD</button>';

Just use onclick="myFunction()" instead onclick="myFunction('pd')" and then you can initiate the function be like

myFunction(){
  echo "I am your function";
}

This is not really a PHP question so much as a how to escape quotes question. So, the following example illustrates using JavaScript:

function myFunction(str){
  console.log("Button " + str + " clicked");
}

var d = document;
d.g = d.getElementById;

var resuult = d.g("result");

result.innerHTML = '<button class="btn" onclick="myFunction(\'pd\')">PD</button>';

result.innerHTML += '<button class="btn" onclick="myFunction(\'pd\')">PD</button>';
<div id="result"></div>

The same string will work in PHP, too, as follows:

<?php
    echo '<button class="btn" onclick="myFunction(\'pd\')">PD</button>';
?>

Working with strings of HTML can be tricky. In this case, the string for each button uses single quotes while the attributes are enclosed by double quotes. For the onclick event attribute, the function parameter must use escaped single quotes to avoid error.

What would be preferable to avoid errors, would be to use the DOM to append the button element. Also, the onclick event attribute would be better off if it were removed from the button tag. So you could instead create JavaScript similar to the following:

var d = document;
d.g = document.getElementById;

var result = d.g("result");
var btnNode = d.createElement("button");
var textNode = d.createTextNode("PD");

btnNode.appendChild(textNode);
result.appendChild(btnNode);

btnNode.onclick = function(){
     console.log("you clicked me");
};
<div id="result"></div>

If put the JavaScript in its own file, such as "myPDButton.js", then the PHP could be as simple as:

<?php
  echo "<script src='myPDButton.js'></script>";
?>

OR, using heredoc syntax:

 <?php

 echo <<<EOT
 <script src="myPDButton.js"></script>
 EOT;

 ?>

Unless, of course you used the DOM to append this script element :)

There is a certain principal in PHP called KISS ("Keep it simple ...") for a good reason and the more you can simplify, the more robust your code is likely to be.

</div>

<?php  
echo '<button class="btn" onclick="myFunction(\'pd\')">PD</button>';?>

<script>
    function myFunction(){
        alert('alert from pd');
    }
</script>