简体   繁体   English

PHP函数中的Jquery-数字格式

[英]Jquery inside a PHP function - Number format

I'm trying to run a javascript/jquery code inside a PHP function in wordpress. 我正在尝试在wordpress的PHP函数中运行javascript / jquery代码。 Actually I found this code at this link: http://jsfiddle.net/fXrv2/ 实际上,我在以下链接上找到了此代码: http : //jsfiddle.net/fXrv2/

As you can see, it works perfectly. 如您所见,它运行完美。 But it seems that something is missing in my final code bellow, because the text-field isn't able to auto complete the number format. 但是似乎在我的最终代码中缺少某些内容,因为文本字段无法自动完成数字格式。

Any idea why is it not working? 知道为什么它不起作用吗?

    <?php

    function teste() {
        ?>

        <script type="text/javascript">
            $('input.number').keyup(function(event) {

                // skip for arrow keys
                if(event.which >= 37 && event.which <= 40){
                    event.preventDefault();
                }

                $(this).val(function(index, value) {
                    return value
                        .replace(/\D/g, "")
                        .replace(/([0-9])([0-9]{2})$/, '$1.$2')
                        .replace(/\B(?=(\d{3})+(?!\d)\.?)/g, ",")
                        ;
                });
            });
        </script>

        <input type="text" class="number">

        <?php
    }

Since that JS is all client-side you're going to have more consistent results including that script completely separate from your PHP. 由于该JS都是客户端,因此您将获得更一致的结果,包括该脚本与PHP完全分开。 If your theme already has a JavaScript file you can add it to that's great, or you can add it to a separate .js file and enqueue that file using wp_enqueue_scripts() . 如果您的主题已经有一个JavaScript文件,则可以将其添加到该文件中,也可以将其添加到单独的.js文件中,然后使用wp_enqueue_scripts()将其放入队列

Whichever way you choose you'll want to invoke it within document.ready() or on window load ( see the jQuery docs ) to make sure that the input element you're trying to select is available for the JS to find. 无论选择哪种方式,都需要在document.ready()或窗口加载时( 请参阅jQuery docs )调用它,以确保要选择的输入元素可供JS查找。 In the JS fiddle you linked to it's set to use the JS onLoad and that likely makes all the difference over your current inline script. 在链接到JS的小提琴中,将其设置为使用JS onLoad,这可能会与当前的内联脚本产生很大的不同。

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

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