简体   繁体   中英

Why doesn't Chrome allow changing of style tag via JS?

I'm running this code:

    jQuery.get("http://email.hackmailer.com/checkuser.php?email=".concat(document.getElementById('name').value).concat(document.getElementById('domain').value), function(data) {
        if(data == "true") {
            document.getElementById('containerThree').style = "background-color:#20bb47;";
        }else{
            document.getElementById('containerThree').style = "background-color:#b33535;";
        }
        document.getElementById('avail').style = "color:#272727;";
        document.getElementById('emt').style = "color:#272727;";
    });

It works fine in FireFox, but in chrome not at all. I've tried using .style.background = "#mycolorcode" but it still doesn't work in chrome(and in that case, firefox too).

Try this:

if (data === 'true') {
  document.getElementById('containerThree').style.backgroundColor = '#20bb47';
} else {
  document.getElementById('containerThree').style.backgroundColor = '#b33535';
}

http://devdocs.io/html/element/style

http://youmightnotneedjquery.com/

NOTE: 'true' is a string. You would most likely would rather use the Boolean true .

Based on the latest edit to your question , does this cleanup of your surrounding code help?

jQuery.get('http://email.hackmailer.com/checkuser.php?email='
           .concat(document.getElementById('name').value)
           .concat(document.getElementById('domain').value), 

            function (data) {

              if (data === true) {
                document.getElementById('containerThree').style.backgroundColor = '#20bb47';
              } else {
                document.getElementById('containerThree').style.backgroundColor = '#b33535';
              }

              document.getElementById('avail').style.color = '#272727';
              document.getElementById('emt').style.color = '#272727';

});

You don't need to send a string as 'true' to check a condition. Use it like:

var data = true; //use boolean but not 'true' as string.

Then you can simple use it as follows:

jQuery.get("http://email.hackmailer.com/checkuser.php?email=" + document.getElementById('name').value + document.getElementById('domain').value, function(data) {
    var colorValue = "#272727";
    document.getElementById('containerThree').style.backgroundColor = data == "true"?"#20bb47":"#b33535";
    document.getElementById('avail').style.color = colorValue;
    document.getElementById('emt').style.color = colorValue;
});

BTW, I am not sure how .style = "background-color:#20bb47;"; is working for you.

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