Is it possible to return the Javascript result in HTML with Javascript only?

Asked

Viewed 949 times

2

How can I return the result of this code in HTML: The main function of the code is at the end of the code...

//estrutura do problema.
var problem = {
    init_state:"III",
    end_state:"VIII",
    action: [
        ["I",1,280],["II",2,280],['IV',3,240],["V",4,770],['VI',5,180]
        ,["VIII",6,770],['VII',7,1330],['VII',8,1000],['IX',9,830],['VIII',10,1400]
        ],
    costs:[
        ["I",1,280],["II",1,280],["III",2,230],['III',3,240],["III",8,1000]
        ,["IV",4,770],['IV',6,770],['IV',7,1330],['V',5,180],['VII',10,830],['VII',9,1400]
        ]
}
//Variável que receberá a solução.
var soluction = null;
//Variável que receberá a borda.
var border = [];
//Função para cria o nó.
function createNode(init_state,noFather,action,cost,profundity){
    var node = {
        state:init_state,
        noFather: noFather,
        action:action,
        cost:cost,
        profundity:profundity
    }

    return node;
}
//Função que fará os testes.
function test(problem,node){
    console.log("Testando...\n Atual:",node.state," Objetivo:",problem.end_state," Ação:",node.action);
    if(problem.end_state === node.state){
        soluction = node;
        console.log("Encontramos o objetivo:",soluction);
        return true;
    }else{
       return false 
    }
}
//Função para remover o primeiro da borda.
function removerFisrt(border){
    var no;
    if(border){ 
        no = border[0];
        border.splice(0,1);
    }
    return no;
}
//Função que pegará os nós sucessores.
function successor(no,problem){

    var actions_possibles = [];
    //Procurando as ações possiveis.
    for(var i =0; i < Object.keys(problem.costs).length;i++){
        if(problem.costs[i][0]===no.state){
            actions_possibles.push(problem.costs[i][1]);
        }
    }
    //Procurando os problemas ações.
    var problem_actions = [];
    for(var i=0; i< Object.keys(actions_possibles).length;i++){
        for(var j =0; j <Object.keys(problem.action).length;j++){
            if(problem.action[j][1] === actions_possibles[i]){
                problem_actions.push(problem.action[j]);
            }
        }
    }

    return problem_actions;

}
//Função que adicionará os nós sucessores em uma borda.
function addInBorder(border,sucessors){
    for(var i =0;i<Object.keys(sucessors).length;i++){
        border.push(sucessors[i]);
    }
}
//Função para expadir.
function expand(node,problem){
   var sucessors = [];
   var problem_actions = [];
   problem_actions = successor(node,problem);
   for(var i =0; i < Object.keys(problem_actions).length;i++){
        var node = createNode(problem_actions[i][0],node.state,problem_actions[i][1],problem_actions[i][2],node.profundity+1);
        sucessors.push(node);
   }
   return sucessors;
}
//Funçao que busca na árvore.
function searchInTree(problem,border){

    border.push(createNode(problem.init_state,null,null,0,0)); 
    while(soluction === null){
        if(border===null || border === undefined || ''){console.log("Ocorreu uma falha");}
        var node = removerFisrt(border);
        if(test(problem,node)){console.log("Chegamos ao destino:",problem.end_state," pela à ação ", node.action," com o custo de ", node.cost,"."); break}
        addInBorder(border,expand(node,problem));
    }
}
//Funçao princiapl onde o fluxo começa ao receber o evento click.
var main = function(){
    console.log("Objetivo Final:",problem.end_state," \n\n\n");
    searchInTree(problem,border);
}

HTML is like this:

<!DOCTYPE html>
<html>
<head>
    <title>Algoritmo de Busca</title>
    <link rel="stylesheet" type="text/css" href="bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>

    <div class="container" id="box">
        <button class="btn btn-primary" id="btn" onclick="javascript:main();" >Começar</button>
    </div>
    <div class="container" id="resultado">

    </div>

<script src="algoritmo.js" ></script>
</body>
</html>

The expected output in HTML is as follows:

inserir a descrição da imagem aqui

When you click the start button, the code displays the algorithm search in the HTML div. This is possible only with javascript?

  • will document.getElementByID('resultado').innerHTML = "Objetivo Final:" + problem.end_state; doesn’t solve?

  • Or you can put that in a function and use instead of console.log. If you don’t know, I can make an example

  • @Ricardopontual shows an example, Thanks !

2 answers

1

For you to print directly in html with javascript can be like this:

var divR = document.getElementById('resultado');

var p;
var text;

for ( var i = 0; i < 20; i++ ) {
    if ( i % 2 == 0 ) {
        p = document.createElement( 'p' );
        text = document.createTextNode( 'par: ' + i  ) ;
        p.append( text );

        divR.appendChild( p );
    }
    else {
        console.log( 'ímpar: ' + i );
    }
}

Print pairs in HTML and odd in the console, in this case I am creating a 'P' element, filling it with text and adding as a child in the result div. I hope it helped you.

0


Here is an example of a function to log in (just switch from console.log to'log in'):

function logar() {
     // onde vai ser escrito o log
     var logger = document.getElementById('resultado');
     // verifica da parâmetro passaod para a função, separado por vírgula
     for (var i = 0; i < arguments.length; i++) {
        //se for um objeto, serializa para melhorar a visualização e adiciona na div, e depois pula uma linha
        if (typeof arguments[i] == 'object') {
            logger.innerHTML += (JSON && JSON.stringify ? JSON.stringify(arguments[i], undefined, 2) : arguments[i]) + '<br />';
        } else { 
            //senão, simplesmente adiciona na div
            logger.innerHTML += arguments[i] + ' ';
        }
    }
}

Copied from this example, which "overwrites" the function console.log and adds comments: http://jsfiddle.net/arunpjohny/mGDet/

  • It worked really well! Thanks there. Now I’m just having trouble skipping the lines, I’ll see it here. The most important thing has already been done. Thanks! ;D

  • Skip the lines? Just by a br here: logger.innerHTML += arguments[i] + '<br />' ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.