简体   繁体   中英

Javascript Button OnClick not working, method runs normally

I am trying to create a button in Javascript, that when clicked will send an AJAX Request to some PHP Code.

I have already setup 3 buttons that do the same thing and they are all working fine.

The most bizarre thing is that if I call the method directly it runs fine.

The code for the button:

<button id="toggle-button">Toggle</button>

The Javascript:

var toggleButton = document.getElementById('toggle-button');
...
function init()
{
    ...
    toggleButton.onClick = handleToggleClick;
    ...
}

function handleToggleClick(event)
{
    alert("Sending Request");
    var admin_url = "http://localhost/wp-admin/admin-ajax.php";
    var data = {
        action : 'toggle',
    }
    $.post(admin_url, data, function(resp) {
        alert(resp);
    });
}

I have called the following in the Chrome Developer Tools Console:

handleToggleClick(null); // The request is sent
autoScheduleButton.onClick(); // The request is sent
autoScheduleButton.onClick; //It prints out the function
autoScheduleButton; //It displays the HTML of the button.

As I mentioned before there are 3 other buttons which do practically the same thing and work fine, so I really can't see why this isn't working.

Hopefully this is just something really obvious i missed.

EDIT:

Originally I made an error while anonymising the code, the code above is now correct in the init method.

Previous code: function init() { ... toggleButton.onClick() = handleToggleClick; ... }

In init function you have code like toggleButton.onClick() = handleToggleClick; . This means that you assign to the result of the onClick() function to the handleToggleClick .

You need to assign to onClick and not call it. Try this instead toggleButton.onClick = handleToggleClick;

function init()
{
    ...
    toggleButton.onClick = handleToggleClick;
    ...
}

The code toggleButton.onClick() = handleToggleClick; in the init function is not a right assignment. It actually means You are calling onClick function on toggleButton and then assigning to the result handleToggleClick .

change it ti toggleButton.onClick= handleToggleClick meaning you are listening to a click event on toggleButton and then calling function handleToggleClick

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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