Javascript 如何在单个wordpress页面中添加jquery代码?
我有一个需要jQuery的脚本,我不知道如何将它添加到单个wordress页面中。 我寻找了许多解决方案,但它们太难让我理解Javascript 如何在单个wordpress页面中添加jquery代码?,javascript,jquery,ajax,wordpress,Javascript,Jquery,Ajax,Wordpress,我有一个需要jQuery的脚本,我不知道如何将它添加到单个wordress页面中。 我寻找了许多解决方案,但它们太难让我理解 <script> $(document).ready(function(e) { $('#checkboxtest').change(function(){ if( $('#checkboxtest').prop('checked') ) {checkboxstatus = "YES";} else
<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>
$(文档).ready(函数(e){
$('#checkboxtest')。更改(函数(){
if($('checkboxtest').prop('checked'))
{checkboxstatus=“是”;}
其他的
{checkboxstatus=“否”;}
$.ajax({
类型:“POST”,
url:“checkboxtestbackend.php”,
数据:{checkboxstatus:checkboxstatus},
})
});
});
有很多方法可以将javascript添加到WordPress中
最简单的方法是使用像这样的插件在WordPress上需要的地方添加脚本
另一种方法是更新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 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; ?>
$(文档).ready(函数(e){
$('#checkboxtest')。更改(函数(){
if($('checkboxtest').prop('checked'))
{checkboxstatus=“是”;}
其他的
{checkboxstatus=“否”;}
$.ajax({
类型:“POST”,
url:“checkboxtestbackend.php”,
数据:{checkboxstatus:checkboxstatus},
})
});
});
使用如下代码:
<?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');
除了下面提供的答案之外,您还应该使用
enqueue_script()
根据wordpress codex从单独的文件中检索jquery。
/**
* 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' );