Load function js automatically e for several divs

0

My problem is as follows.

I have two or more divs on my page and want to automatically call a function for them by loading the page in question. And at the same time I call these functions I want to pass some parameters so that they are handled in js and returned.

I'll try to explain it some other way.

<div id="a" class="" teste('lala')>
    <span></span>
</div>

<div id="b" class="" teste('papa')>
    <span></span>
</div>

<div id="c" class="" teste('caca')>
    <span></span>
</div>

<div id="d" class="" teste('baba')>
    <span></span>
</div>


function teste (parametro){
    var parametro = parametro;

    /* Preciso neste momento pegar a div que esta chamando a função e atribuir o valor passado para a sua respectiva div. Isso é possível? */
}

Summarizing what I need you to help me: - Make the div call the function when loading the page, I wanted to use onLoad, but it only works for the body - Recognize the div that is calling the function and assign the parameter to some daughter of it (in this example to span).

Remembering that all js will be in an external file.

Who can help me, thank you.

    
asked by anonymous 29.04.2017 / 02:56

2 answers

1

You have to create events for that to happen.

With Jquery:

$('#a').ready(function() {
    teste('lala');
});

$('#b').ready(function() {
    teste('papa');
});

$('#c').ready(function() {
    teste('caca');
});

$('#d').ready(function() {
    teste('caca');
});

function teste (parametro){
    var parametro = parametro;
}

Note: If you have a complex interface or a high level of dynamic content, I suggest using some Javascript framework.

    
29.04.2017 / 04:17
2

You can use onload on any element in html how can you view but it does not have only this means for this. To get the child element, you first have to know which element

<div id="a" class="" onload="teste(this,'lala')">
<span></span>
</div>
<script>
function teste (elemento,parametro){
console.log(elemento,parametro);
//elemento é todas as propriedades do elemento que foi carregado
elemento.children[0].innerText = paramentro;//carregando o texto pelo parametro usado
 }
</script>

But as I said, you have better ways to do this.

    
29.04.2017 / 04:25