繁体   English   中英

如何在单个 wordpress 页面中添加 jquery 代码?

[英]How Can i add jquery code in single wordpress page?

我有一个需要 jQuery 的脚本,我不知道如何将它添加到单个 wordress 页面中。 我寻找了许多解决方案,但它们对我来说太难理解了。

<script>
$(document).ready(function(e) {
$('#checkboxtest').change(function(){
    if( $('#checkboxtest').prop('checked') )
       {checkboxstatus = "YES";}
       else
       {checkboxstatus = "NO";}
$.ajax({
        type: "POST",
        url: "checkboxtestbackend.php",
        data: {checkboxstatus: checkboxstatus},
        })
        
});
});
</script>

尝试这个:

<?php if (is_page('my-page-slug')): ?>
<script>
$(document).ready(function(e) {
$('#checkboxtest').change(function(){
    if( $('#checkboxtest').prop('checked') )
       {checkboxstatus = "YES";}
       else
       {checkboxstatus = "NO";}
$.ajax({
        type: "POST",
        url: "checkboxtestbackend.php",
        data: {checkboxstatus: checkboxstatus},
        })
});
});
</script>
<?php endif; ?>

有很多方法可以将 javascript 添加到 WordPress 中。

最简单的方法是使用像这样的插件css javascript 工具箱在 WordPress 上的需要添加脚本。

另一种方法是更新您的 WordPress 模板并在需要的地方插入您的代码。 此链接为您提供了如何实现此目的的完整示例: add-javascript-to-wordpress

首先-您应该重写您的 jQuery 包装器,以使代码在 WP 页面中工作:

jQuery(function($) {
    $('#checkboxtest').change(function(){
        if( $('#checkboxtest').prop('checked') )
           {checkboxstatus = "YES";}
           else
           {checkboxstatus = "NO";}
    $.ajax({
            type: "POST",
            url: "checkboxtestbackend.php",
            data: {checkboxstatus: checkboxstatus},
            })
            
    });
});

现在您可以通过两种方式将此代码添加到 Wordpress 页面:

为自定义代码片段使用插件(比如这个

或者,如果您的页面使用的是自定义编码模板,您可以直接粘贴

<script>
...
</script>

用您的代码标记,在您需要的地方。

使用如下代码:

  <?php
    function myscript() {
        // if ( is_single() && 'post' == get_post_type() ) {
        // if ( is_singular( 'book' ) ) {  // book is a custom post type 
        if ( is_single()) {
            ?>
            <script type="text/javascript">
                alert("Hello! I am Added");
    
            </script>
        <?php
        }
    }
    add_action('wp_footer', 'myscript');

另一个例子:

/**
 * Proper way to enqueue scripts and styles.
 */
function wpdocs_theme_name_scripts() {
    // if ( is_single() && 'post' == get_post_type() ) {
    // if ( is_singular( 'book' ) ) {  // book is a custom post type 
    if ( is_single()) {
        wp_enqueue_style( 'style-name', get_stylesheet_uri() );
        wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/example.js', array('jquery'), '1.0.0', true );
    }
}
add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );

暂无
暂无

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

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