简体   繁体   English

如何在Wordpress文件“ single.php”中添加自定义javascript代码

[英]How to add custom javascript code in the Wordpress file “single.php”

I have a problem with adding custom javascript code in the Wordpress file "single.php" I follow these steps, but it didn't work How to add JavaScript to WordPress PHP file? 我按照以下步骤在Wordpress文件“ single.php”中添加自定义javascript代码时遇到问题,但没有成功。 如何将JavaScript添加到WordPress PHP文件中? I dont know if that's happening due to WordPress security purposes or not Btw, this is the javascript function 我不知道这是出于WordPress安全目的还是Btw,这是javascript函数

<script type="text/javascript">

function room_combobox() {
var text = "";
var i;
for (i = 0; i < 7; i++) {
text += "<option value=+i+>"+i+"</option>" +"<br>";
}
document.getElementById("combo").innerHTML = "<select name= &#8220; room-adults &#8221; id= &#8220; single-room-adult-selection &#8221; ><option><?php _e( &#8220; No. adults &#8221; , &#8220; nation &#8221; ); ?></option>"+text+"</select>";
}

</script>

Thanks! 谢谢!

As adeneo mentioned, the preferred way to do this is to put the script in it's own file and link to it. 正如adeneo所述,执行此操作的首选方法是将脚本放入其自己的文件中并链接到该文件。 Go into the functions.php file for your theme and add the following action: 进入您的主题的functions.php文件,并添加以下操作:

add_action("wp_enqueue_scripts", function() {
     if (is_single()) {
         wp_enqueue_script($script_handle, $path_to_script, [$script_dependencies]);
     }
});

$script_handle can be anything you like. $script_handle可以是您喜欢的任何东西。 It's a unique key that identifies your script. 这是标识脚本的唯一键。

$path_to_script should point to the location of the js script. $path_to_script应该指向js脚本的位置。

[$script_dependencies] should be an array of handles to other js scripts your script depends on. [$script_dependencies]应该是脚本所依赖的其他js脚本的句柄数组。 Wordpress has a list of built in libraries like 'jquery'. Wordpress有一个内置库列表,例如“ jquery”。 See here: Default Wordpress Scripts . 请参阅此处: 默认的Wordpress脚本

Only the first two parameters are required. 仅需要前两个参数。 You can also add the version and whether or not to embed the script tags on the top or bottom of the page. 您还可以添加版本以及是否在页面顶部或底部嵌入脚本标签。 That's covered in the documentation for wp_enqueue_script if you want to know more. 如果您想了解更多信息,请wp_enqueue_script的文档。

Note also that the issue with your js code, if I'm reading this correctly, is that you're not actually calling the room_combobox function. 还请注意,如果我正确阅读room_combobox ,则js代码的问题是您实际上并未调用room_combobox函数。 Add the following to your script--It will trigger on document load: 将以下内容添加到脚本中-它将在文档加载时触发:

jQuery(document).ready(function() {
    room_combobox()
});

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

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