문제 설명
WordPress에서 Simple Jquery Click이 작동하지 않음 (Simple Jquery Click not working in WordPress)
저는
.
내 javascript
파일을 바닥글에 포함했습니다.
내 자바스크립트 코드는
jQuery( document ).ready(function($) {
console.log( "ready!" );
$("#start‑reading").click(function() {
console.log("click");
});
});
한 번의 jQuery 클릭 기능. 여기 콘솔에서 ready
메시지를 볼 수 있습니다. 그러나 ID가 start‑reading
인 요소를 클릭하면 아무 일도 일어나지 않습니다.
여기에 마크업이 있습니다.
<button id="start‑reading">
</button>
저는 wordpress를 처음 사용합니다. 제가 잘못하고 있는 wordpress realted가 있습니까? 이것은 WordPress가 아닌 환경에서 작동해야 하기 때문입니다.
참조 솔루션
방법 1:
WP makes sure it only loads scripts once. So it collects all script requests from all plugins and decides the correct order based on dependencies and priority.
To correctly add your script in WordPress you need to use wp_enqueue_script().
방법 2:
Keep use jQuery
instead of $
. Just like the below code.
jQuery(document).ready(function() {
console.log( "ready!" );
jQuery("#start‑reading").click(function() {
console.log("click");
});
});
Check your element ID whether it's #start‑reading
Or #start_reading
.
방법 3:
Use the recommended way, add these code to functions.php
function your_theme_scripts() {
wp_enqueue_script( 'your‑theme‑script', get_template_directory_uri() . '/js/script.js', array( 'jquery' ), '', true );
}
add_action( 'wp_enqueue_scripts', 'your_theme_scripts' );
jQuery is already integrated to WordPress, now you can wirte jQuery code to the script.js file.
방법 4:
If it is a dynamically added button (e.g. during the execution of some code), you can use onclcick
in the HTML code of the button.
jQuery('#parent')
.html('<button onclick="test_func()">Test</button>');
BUT the declaration of the target function ( test_func()
) must be in the root of the file (not function in function)
(by Sooraj、tao、Kvvaradha、Nasir Ahmed、Anar Salimkhanov)