简体   繁体   English

从PHP调用函数javascript

[英]Call function javascript from PHP

---- avarias_js.js ---- ---- avarias_js.js ----

function limpar() { alert('test'); }

---- avarias.php ---- ---- avarias.php ----

add_action('init','initjs');

function initjs() {

    wp_enqueue_script( 'avarias_js', plugins_url( 'avarias_js.js', __FILE__ )); 

}

how do i call the function 'limpar()' on the javascript file with a click of a button? 我如何通过单击按钮在javascript文件上调用函数“ limpar()”?

PHP runs on the server side and Javascript runs on the client side (unless you are using Node.JS) You will want to just add Javascript markup into the HTML page so that it will call the Javascript code. PHP在服务器端运行,而Javascript在客户端运行(除非您使用的是Node.JS)。您只想在HTML页面中添加Javascript标记,以便它可以调用Javascript代码。 There is no need to have PHP call to client-executed Javascript. 无需通过PHP调用客户端执行的Javascript。

From what I read, basically you will want to insert an HTML button. 根据我的阅读,基本上,您将需要插入一个HTML按钮。

<button onclick="limpar();">Click Here!</button>

HTML is the way to go for this.. If I have understood you correctly. HTML是解决此问题的方法。如果我正确理解了您。 Or you can echo the HTML code in PHP. 或者,您可以在PHP中回显HTML代码。 Whatever floats your boat. 无论您的船浮在水上。

you have to call your function inside javascript with something like this (use of jquery): 您必须使用类似以下内容(使用jquery)在javascript中调用函数:

avarias_js.js : avarias_js.js:

$(document).ready(function(){
    $("#buttonId").click(limpar);
});

function limpar(){
    alert('something');
}

If you enqueue avarias_js.js properly (make sure its loading on the front side with your browser's developer tools) you can use that JS file and the functions within it. 如果正确排队avarias_js.js(确保使用浏览器的开发人员工具将其加载在正面),则可以使用该JS文件及其中的功能。

To use function limpar() create a button in HTML on any page or post template that avarias_js.js is loading on like so: 要使用limpar()函数,请在要加载avarias_js.js的任何页面或帖子模板上的HTML中创建一个按钮,如下所示:

<input name="butt" type="button" id="butt">

Within your JS use this jQuery snippet to "listen" for a click on the button: 在您的JS中,使用以下jQuery代码段“监听”按钮:

$("#butt").on("click", function(event){
    // alert($(this).text());
    limpar();
});

I would recommend researching AJAX if I interpret your question's goals correctly. 如果我正确地解释了您的问题的目标,我建议您研究AJAX。 Within WordPress it is a bit more complicated than standard AJAX calls to PHP. 在WordPress中,它比对PHP的标准AJAX调用更为复杂。

NOTE: @dougjore method will immediately fire the function on click. 注意:@dougjore方法将立即在单击时触发该功能。 My code listens for a click. 我的代码监听点击。

<?php
echo '<!script type="text/javascript">limpar();<!/script>'
?>

Remove the ! 去除 ! after each "<", otherwise stackoverflow wont let me post. 在每个“ <”之后,否则stackoverflow不会让我发布。 I did not test it, just suggesting. 我没有测试,只是建议。 Regards. 问候。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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