Php Onclick Function With "" And '' Does Not Work

Bạn đang xem: Php onclick function with "" and '' does not work


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

myFunction() emang đến "I am your function";


This is not really a PHPhường question so much as a how khổng lồ 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 = "PD";result.innerHTML += "PD";

The same string will work in PHPhường, too, as follows:

PD";?>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 khổng lồ avoid error.

What would be preferable lớn avoid errors, would be to lớn use the DOM lớn appover the button element. Also, the onclick sự kiện attribute would be better off if it were removed from the button tag. So you could instead create JavaScript similar khổng lồ 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.onclichồng = function() console.log("you clicked me");;

Xem thêm: Qhht Là Gì - Phoebe Hall: Tiếng Việt

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

OR, using heredoc syntax:

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

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



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

eđến "PD";


Thanks for contributing an answer to Staông xã Overflow!

Please be sure to lớn answer the question. Provide details & giới thiệu your research!

But avoid

Asking for help, clarification, or responding to lớn other answers.Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.

Post Your Answer Disthẻ

By clicking “Post Your Answer”, you agree khổng lồ our terms of service, privacy policy & cookie policy

site kiến thiết / logo sản phẩm © 2021 Stachồng Exchange Inc; user contributions licensed under cc by-sa. rev2021.3.3.38704