简体   繁体   中英

Updating div background image in javascript

I've found similar examples of what I'm trying to accomplish here, but I'm not sure exactly what I'm doing wrong in my implementation.

I've got a div that has 2 components: a background image and 5 labels.

    <div id="graph" class="graphs" style="display: block">
        <div id="chart">
        </div>
        <div id="symbol" class="symbols">
            <div id="symbol1" class="ticker" onclick="showg()"></div>
            <div id="symbol2" class="ticker" onclick="showg()"></div>
            <div id="symbol3" class="ticker" onclick="showg()"></div>
            <div id="symbol4" class="ticker" onclick="showg()"></div>
            <div id="symbol5" class="ticker" onclick="showg()"></div>
        </div>
    </div>

My JavasScript is as follows:

var portfolios = [
{ "ticker1" : "LLNW", "ticker2" : "AOL", "ticker3" : "DATA", "ticker4" : "PUBN", "ticker5" : "YUME",  }, ];
document.getElementById("symbol1").innerHTML = portfolios[0].ticker1;
document.getElementById("symbol2").innerHTML = portfolios[0].ticker2;
document.getElementById("symbol3").innerHTML = portfolios[0].ticker3;
document.getElementById("symbol4").innerHTML = portfolios[0].ticker4;
document.getElementById("symbol5").innerHTML = portfolios[0].ticker5;

function showg(){
var currentTicker = this.innerText;
document.getElementById("chart").style.backgroundImage= "url('"+ currentTicker +" -    GRAPH.png')";}

Each of my images is named currentTicker-GRAPH.png (ie LLNW-GRAPH.png).

What I think I'm doing is setting the innerHTML of the div I'm running the showg() function on and calling it currentTicker. I'm then trying to use that + '-GRAPH.png' to change the background image style. (for the time being, my images are all in the same folder as my .js, .css, .html files).

I'm pretty sure I'm doing the currentTicker variable declaration incorrectly...but not sure how.

Any help will be greatly appreciated.

You need to pass the element in the function call like this:

onclick="showg(this)"

And your function will be :

function showg(el) {
    var currentTicker = el.innerText;
    document.getElementById("chart").style.backgroundImage= "url('"+ currentTicker +" -    GRAPH.png')";
}

Because this represents the window element inside the function, not the clicked element.

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