سؤال

<input type="button" onclick="restartBattle('Battle=Trainer&amp;BattleID=294','nFOgYlQGjn')" value="Restart Battle" style="width:160px;">

That is the coding of the button. Unless the restart code is entered as well (it's dynamic, changes every refresh), I can't click the button with the methods of Javascript or jQuery that I've tried.

'nFOgYlQGjn' is the restartCode. I've tried this coding to click the button, but it won't work.

var btn = document.querySelector('input[value="Restart Battle"]');
if (btn) {
    var x = Math.round((Math.random() * 90) + 663);
    var y = Math.round((Math.random() * 15) + 589);

    function restartBattle(url, restartCode) {
        $('#battleContent').html('Loading...<br /><br />'); 
        $('#battle').load('http://tpkrpg.net/core/battles/battle.php?'+url+'&RestartCode='+restartCode);
    }
    //btn.click();
}

This should work, since I took the function restartBattle part out of the source code, but it still won't work. Any ideas?

هل كانت مفيدة؟

المحلول

Pass the data as an object to the script. You could use on('click', method here) or click(method here) on the id of the input tag. Make sure jquery is included too.

button:

<input type="button" value="Restart Battle" id="restart" />

css:

#restart
{
    width:160px;
}

jQuery:

/* sample how to get the values as variables

method one, static hard coded

var battleType = "Training";
var battleId =  294;
var restartCode = "nFOgYlQGjn";

method 2, php set via echo, requires page to be created by php, example uses theoretical data returned from a database stored as an associative array but could be changed for variables

var battleType = <?php echo $battle['training']; ?>;
var battleId =  <?php echo $battle['id']; ?>;
var restartCode = <?php echo $battle['restart_code']; ?>;

*/

function restartBattle( varz )
{
        $("#battleContent").html("Loading...<br /><br />"); 
        $("#battle").load("http://tpkrpg.net/core/battles/battle.php", {Battle : varz.data.type, BattleId : varz.data.id, RestartCode : varz.data.code});
}

// handle the click of the button and execute functon with passed data.
$("#restart").on("click", { type : "Training", id : 294, code : "nFOgYlQGjn" }, restartBattle);

Your php code needs to check for this data being passed to it so it can return the data either some json, html, or plain text using echo.

battle.php:

$restartCode = ( ( isset( $_REQUEST['RestartCode'] ) ) ? $_REQUEST['RestartCode'] : false );

if( !$restartCode ) echo "Error : No restart code!";

That is a start, but you need to create variables that hold the data being sent to the php script or else it's hard coded to those values.

See method API

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top