Load js function automatically and for various Ivs

Asked

Viewed 2,987 times

0

My problem is this.

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

I’ll try to explain it another 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? */
}

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

Remembering that all js will be in an external file.

Anyone who can help me, I thank.

2 answers

2

You can use onload on any element in html as you can see But you don’t have just this medium for it. To catch the child element, first you 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 like I said, you have better ways of doing this.

  • What would be the best way to do that?

1


You have to create events for such a thing 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.

  • It would be dynamical content. What I’m trying to do, is a dynamical Countdown. The only way q found was by js to php with ajax. But it’s still too complicated.

  • I’m having trouble calling the function automatically for the N Ncds on the screen. The Countdown function I managed to assemble, this beautiful dmais. More call this function separately for each Countdown on the screen is being my weak point.

Browser other questions tagged

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