欢迎使用WordPress StackExchange!正如TomJ Nowell在问题评论中提到的,当使用WordPress时,通过外部javascript文件实现javascript交互将更加安全。
为此,您需要完成三个步骤:
Create your JS file with the event that fires onkeyup:
(function (window, $) {
document.getElementById("myInput").addEventListener("keyup", myFunction);
function myFunction() {
var input, filter, table, tr, td, i, txtValue;
input = this; //CHANGE THIS LINE. Assigning "this", which is your input, gives you access to the value, etc.
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
})(window);
在上面的示例中,您应该使用一种或另一种解决方案(vanilla JS或jQuery),而不是两者都使用。
一旦您将文件放在主题中(例如wp-content/themes/twentytwenty/js/your-custom-file.js
), you will need to add it to your theme via wp_enqueue_script
.
<?php
//Inside functions.php of your theme.
add_action(\'wp_enqueue_scripts\', \'custom_enqueue_script\');
function custom_enqueue_script(){
wp_enqueue_script(\'custom-script\', get_stylesheet_directory_uri().\'/js/your-custom-file.js\', array(\'jQuery\'), false, true);
}
然后将自定义JS文件添加到主题中。我建议您浏览下面的其他链接,以了解WordPress如何处理JS文件,但以上内容将帮助您开始学习。