简体   繁体   中英

Javascript on button click not working

I have a script set up so that I can embed various Facebook Posts on a website. The idea is, it will load a post at random, and then on button click load another. As I am clicking the button, the previous post disappears but the new one that I have called for does not appear.

Can anyone shed any light?

Javascript:

var comps = new Array();

comps[0] = "\"https://www.facebook.com/permalink.php?story_fbid=10151746360309352&id=9212109351\"";

comps[1] = "\"https://www.facebook.com/photo.php?fbid=10202149995929199&set=a.3217789641447.156870.1167545588&type=1\"";

var firstLine = "<div id=\"fb-root\"></div>";

var secondLine = "<div class=\"fb-post\" data-href=";

var thirdLine = " data-width=\"550\"></div>";

var randomComp = firstLine + secondLine + comps[Math.floor(Math.random()* comps.length)] + thirdLine;

window.onload=function(){

document.getElementById('compsContainer').innerHTML = randomComp;
}

function changeComp(){

document.getElementById('compsContainer').innerHTML = randomComp;
}

HTML:

    <div id="compsContainer">



    </div>

    <input type='button' onclick='changeComp()' value='Change Comp'/>

change onlick='' to onclick='javascript:changeComp()' ?

Ok, I misunderstand you question.

try this:

function newFunction(){
    var comps = new Array();

    comps[0] = "\"https://www.facebook.com/permalink.php?story_fbid=10151746360309352&amp;id=9212109351\"";

    comps[1] = "\"https://www.facebook.com/photo.php?fbid=10202149995929199&amp;set=a.3217789641447.156870.1167545588&amp;type=1\"";

    var firstLine = "<div id=\"fb-root\"></div>";

    var secondLine = "<div class=\"fb-post\" data-href=";

    var thirdLine = " data-width=\"550\"></div>";

    var randomComp = firstLine + secondLine + comps[Math.floor(Math.random()* comps.length)] + thirdLine;

    return randomComp;

}

window.onload=function(){

    document.getElementById('compsContainer').innerHTML = newFunction();
}




function changeComp(){



document.getElementById('compsContainer').innerHTML = newFunction();
}

when you call changeComp, it does not run:

var randomComp = firstLine + secondLine + comps[Math.floor(Math.random()* comps.length)] + thirdLine;

so randomComp will be empty.

(updated)

If you don't have any other buttons in the html page. Try this, it will work.

<input type='submit' onsubmit='changeComp()' value='Change Comp' />

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