简体   繁体   中英

Javascript code is working in Firefox but not in IE or Safari

The following code is working with Firefox, but neither with IE 10 nor with Safari:

function showids(id) { //new
   divs = document.getElementsByTagName('div');
   for ( var i = 0; i < divs.length; i++ ) {
    if(divs[i].id.startsWith('id1')) {
        alert(divs[i].id);
        if(divs[i].id.startsWith('id1'+id))
            divs[i].className='one';
        else {
            divs[i].className='two';
            alert('-'+divs[i].id);
        }
      }
     }
 }

Does anybody know the reason?

You can replace the line

if(divs[i].id.startsWith('id1')) {

for the follow line, using an alternative for startsWith

if(divs[i].id.indexOf('id1')==0) {

I added this Code from developer.mozzilla.org:

if (!String.prototype.startsWith) {
  String.prototype.startsWith = function(searchString, position) {
    position = position || 0;
    return this.indexOf(searchString, position) === position;
  };
}

Now my Code is Working. Thanks to all

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