简体   繁体   中英

issue: javascript switch case don't work with my var

I have a issue with js and looking for help...

I'm trying to change the content of a div, but it doesn't work...

My JS:

var headerChange = document.getElementById('myId');
var content = '';

function changeDiv(event) {
        switch (event.target.value) {
            case 'A': {
                content = 'Here the new content case A';
                break;
            }
            case 'B': {
                content = "Here the new content case B...";
                break;
            }
        }
    headerChange.innerHTML = content;
} 

The content (var) don't load the content inside switch case, it return undefined when I click for change the div content... (cus I set the '' value on it... If I change the value, then it change my div content to the value inserted inside it [for examble, if I set var content = 'abc', it loads abc], but I need it working with the values of the switch)

How can I solve it?

thanks.

PS: vannila js.

Hi myId is header element it has no value. It has innerHtml. So you have to use like that.

 var headerChange = document.getElementById('myId'); var content = ''; headerChange.addEventListener('click', changeDiv, false); function changeDiv(event) { console.log('event:',event.target.innerHTML) switch (event.target.innerHTML) { case 'A': { content = 'Here the new content case A'; break; } case 'B': { content = "Here the new content case B..."; break; } } headerChange.innerHTML = content; } function changeDivByButton(action) { switch (action) { case 'A': { content = 'Here the new content case A'; break; } case 'B': { content = "Here the new content case B..."; break; } } headerChange.innerHTML = content; }
 <h1 id="myId">A</h1> <button onclick="changeDivByButton('A')">Click me - A</button> <button onclick="changeDivByButton('B')">Click me - B</button>

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