나는 여기에 간단한 것을 분명히 놓치고있는 것처럼 느껴진다. 그러나 내 인생에서 내가 누락 된 것을 발견 할 수 없다.Wordpress에서 jQuery 스크립트를 올바르게 사용하는 방법은 무엇입니까?
jQuery 함수를 header.php 파일에 직접 포함시키는 것은 "나쁜 습관"입니다. 이것은 필자가 이해할 수있는 것처럼 눈살을 찌푸리게하며, wp_enqueue 함수를 사용하여 함수를 별도의 파일에 보관해야합니다. 준비 문서에 발사한다 How do I add a simple jQuery script to WordPress?
내가 내 header.php에서이 간단한 기능을 가지고 : 나는 솔루션이 여기에 주어진 다음에 시도하고있어
그래서
<script>
// Scroll to Top
jQuery(document).ready(function() {
// Force element to hidden state when page loads
jQuery('.scroll-to-top').hide();
// Check to see if the window is top if not then display button
jQuery(window).scroll(function() {
if (jQuery(this).scrollTop() > 200) {
jQuery('.scroll-to-top').fadeIn();
} else {
jQuery('.scroll-to-top').fadeOut();
}
});
//Click event to scroll to top
jQuery('.scroll-to-top').click(function() {
jQuery('html, body').animate({ scrollTop: 0 }, 800);
return false;
});
});
</script>
을 일을 " 정확하게 ", 내 코드를 가져 와서 myScripts.js (물론 스크립트 태그 제거)에 배치했습니다. 내 functions.php 파일에이 코드를 추가했습니다
<?php
function add_my_script() {
wp_enqueue_script(
'myScripts', // name your script so that you can attach other scripts and de-register, etc.
get_template_directory_uri() . '/js/myScripts.js', // this is the location of your script file
array('jquery') // this array lists the scripts upon which your script depends
);
}
add_action('wp_enqueue_scripts', 'add_my_script');
?>
을하지만 내 페이지를로드 할 때 스크립트가 더 이상 작동하지 않습니다. 지금까지 ...이 줄을 변경 도움을
편집
감사 : 이것에
add_action('wp_enqueue_scripts', 'myScripts');
는 :
add_action('wp_enqueue_scripts', 'add_my_script');
페이지에 나타나는 오류를 해결.
불행히도 코드가 더 이상 페이지에서 실행되지 않는 것처럼 보입니다. 그것이 (문서)이기 때문에 나는 그것이 자동적으로 (그것은 내가 직접 포함 시켰을 때했던 것처럼) 발사해야만한다고 가정하지만,이 방법으로 스크립트를 포함 할 때는 그렇지 않다. 어 ... 생각?
@nevercode와 정확히 같습니다. 'myScripts' **는'add_my_script'와 같지 않습니다 **. 또한 달러 기호를'jQuery (document) .ready (function ($)'라고 쓰면 스크립트 내에서'$ ('# div')'를 쓸 수 있습니다 .. – brasofilo