2016-03-07 2 views
1

Я новичок в Javascript и немного помог, но все еще пытаюсь обернуть голову вокруг решения. Я пытаюсь применить класс .mapplic-active ко всем состояниям, указанным на карте, когда они активны. Пример можно посмотреть здесь: http://test.guidehunts.com/concealed-weapons-permit-reciprocity-map/?location=nv. Я пытаюсь получить строку из location.description, разбивать состояния, а затем применять класс по результатам массива, но сталкиваться с проблемами. Это то, что я пытаюсь изменить.Javascript: применение класса к нескольким идентификаторам для интерактивной карты

function Tooltip() { 
     this.el = null; 
     this.shift = 6; 
     this.drop = 0; 
     this.location = null; 

     this.init = function() { 
      var s = this; 

      // Construct 
      this.el = $('<div></div>').addClass('mapplic-tooltip'); 
      this.close = $('<a></a>').addClass('mapplic-tooltip-close').attr('href', '#').appendTo(this.el); 
      this.close.on('click touchend', function(e) { 
       e.preventDefault(); 
       $('.mapplic-active', self.el).attr('class', 'mapplic-clickable'); 
       if (self.deeplinking) self.deeplinking.clear(); 
       if (!self.o.zoom) zoomTo(0.5, 0.5, 1, 600, 'easeInOutCubic'); 
       s.hide(); 
      }); 
      this.image = $('<img>').addClass('mapplic-tooltip-image').hide().appendTo(this.el); 
      this.title = $('<h4></h4>').addClass('mapplic-tooltip-title').appendTo(this.el); 
      this.content = $('<div></div>').addClass('mapplic-tooltip-content').appendTo(this.el); 
      this.desc = $('<div></div>').addClass('mapplic-tooltip-description').appendTo(this.content); 
      this.link = $('<a>' + mapplic_localization.more_button + '</a>').addClass('mapplic-tooltip-link').attr('href', '#').hide().appendTo(this.el); 
      this.triangle = $('<div></div>').addClass('mapplic-tooltip-triangle').prependTo(this.el); 

      // Append 
      self.map.append(this.el); 
     } 

     this.set = function(location) { 
      if (location) { 
       var s = this; 

       if (location.image) this.image.attr('src', location.image).show(); 
       else this.image.hide(); 

       if (location.link) this.link.attr('href', location.link).show(); 
       else this.link.hide(); 

       this.title.text(location.title); 
       this.desc.html(location.description); 
       this.content[0].scrollTop = 0; 

       this.position(location); 
      } 
     } 

     this.show = function(location) { 
      if (location) { 
       if (location.action == 'none') { 
        this.el.stop().fadeOut(300); 
        return; 
       } 

       var s = this; 

       this.location = location; 
       if (self.hovertip) self.hovertip.hide(); 

       if (location.image) this.image.attr('src', location.image).show(); 
       else this.image.hide(); 

       if (location.link) this.link.attr('href', location.link).show(); 
       else this.link.hide(); 

       this.title.text(location.title); 
       this.desc.html(location.description); 

       // Shift 
       var pinselect = $('.mapplic-pin[data-location="' + location.id + '"]'); 
       if (pinselect.length == 0) { 
        this.shift = 20; 
       } 
       else this.shift = pinselect.height() + 10; 

       // Loading & positioning 
       $('img', this.el).load(function() { 
        s.position(); 
       }); 
       this.position(); 

       // Making it visible 
       this.el.stop().show(); 
      } 
     } 

ответ

0

Я бы рекомендовал использовать JQuery плагин и пытается это

<script src="http://code.jquery.com/jquery-1.12.1.min.js"></script> 
<script> 
    var locations=location.description; 

    //strip tags 
    locations = locations.replace(/(<([^>]+)>)/ig,""); 

    //take states after : 
    locations = locations.split(':'); 

    //set locations to states (after the text) 
    locations=locations[1]; 

    //make states lowercase to match id's 
    locations = locations.toLowerCase(); 

    //remove carriage returns 
    locations = locations.replace('\n',""); 

    //locations var jquery array 
    locations = locations.split(','); 

    //loop array and add class 
    $.each(locations, function(key, state) { 
     $("#"+state).attr("class", "mapplic-active"); 
     //$("#"+state).addClass('mapplic-active'); 
    }); 
</script> 
  1. Поскольку описание имеет другой текст и теги, позволяет лишить HTML-теги, и разделить его с помощью:. Тогда мы бы взяли вторую часть, являющуюся только состояниями.
  2. Вторая команда разделения разбивает состояния на массив.
  3. Каждая команда будет проходить через точки
  4. Затем addClass применяет класс только к состояниям, которые были обратно из описания.
  5. Не забудьте сбросить активные вещества, делая что-то вроде этого

$(".mapplic-active").removeClass('mapplic-active');

+0

Благодаря mjbrancato, я добавил это с еще не повезло. Я вставил фрагмент jquery в this.set = function (location) без везения. Могут ли быть вызваны аббревиатуры верхнего регистра в описании? – kevinje

+0

Состояние и идентификаторы должны быть чувствительны к регистру, поэтому убедитесь, что вы используете правильные. Я сам тестировал этот код, и это сработало для меня. Поэтому, если это не для вас, вам может понадобиться модификация. Что не работает? Предоставляет ли сообщение об ошибке в журнале консоли? – codermjb

+0

Да, это то, что я сейчас получаю в консоли:. util.js: 218 Предупреждение API Карт Google: NoApiKeys https://developers.google.com/maps/documentation/javascript/error-messages#no-api-keys jquery.js? Ver = 1.11.3: 2 Неоткрытый Ошибка: JQMIGRATE: Неверная строка выбора (XSS) – kevinje

Смежные вопросы