0

I've read a lot of similar questions and tried implementing the solutions, but none of them works for me.

This is my code within the page:

<button id="hello" type="button">Try it</button>

And this is the script in the header:

$('#hello').click(hello);

function hello(){
    alert('inside hello function');
};

The only way I could get this exact code to work was when I put the function call directly into the button, like this:

<button id="hello" type="button" onclick="hello();">Try it</button>

But the problem with this is that Wordpress strips that as soon as I switch to the visual page editor.

Any help would be appreciated!

Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120

1 Answers1

0

You should encapsulate your code with the $(document).ready event:

$(document).ready(function() {
    $('#hello').click(hello);
    function hello(){
        alert('inside hello function');
    };
});

And you really don't need a named function for this kind of event handling, you could write your code like this:

$(document).ready(function() {
    $('#hello').click(function(){
        alert('inside hello function');
    });
});
Philippe CARLE
  • 521
  • 3
  • 17