Проблема с скрыть / показать окно выбора в IE7 / 8 - PullRequest
0 голосов
/ 07 августа 2009

Я пытался использовать непроверенную функцию, которую закодировал Джастин Джонсон (спасибо, приятель), но я боролся с ошибками IE. Я новичок в JavaScript.

В основном, что происходит, это:

  1. Пользователь выбирает опцию из поля выбора.
  2. Появляется другое соответствующее поле выбора.
  3. Если есть какое-либо другое поле выбора, которое было выбрано ранее, скрыть его.

В Firefox все в порядке. Я меняю поле выбора, и все работает. Но когда я пытаюсь использовать в IE7 / 8, это ничего не меняет!

Я использовал option9.style.cssText='display: none'; вместо option2.style.display = "none"; , но он тоже не работает.

Вот код (не все выбранные случаи в этом коде, для целей чтения, и код требует оптимизации, я сделаю это позже):

var attachEvento = function(node, event, listener, useCapture) {
  // Method for FF, Opera, Chrome, Safari
  if (window.addEventListener ) {
    node.addEventListener(event, listener, useCapture || false);
  }
  // IE has its own method
  else {
    node.attachEvent('on'+event, listener);
  }
};


// Once the window loads and the DOM is ready, attach the event to the main
attachEvento(window, "load", function() {
  var main_select = document.getElementById("tipos_evento");

   var option1 = document.getElementById("temas_conferencias"),
         option2 = document.getElementById("temas_cursos"),
         option3 = document.getElementById("temas_provas"),
         option4 = document.getElementById("temas_visitas"),
         option5 = document.getElementById("temas_ciencias"),
         option6 = document.getElementById("temas_dancas"),
         option7 = document.getElementById("temas_exposicoes"),
         option8 = document.getElementById("temas_multi"),
         option9 = document.getElementById("temas_musica"),
         option10 = document.getElementById("temas_teatro"),
         option11 = document.getElementById("temas_cultura"),
         option12 = document.getElementById("temas_desporto"),
         option13 = document.getElementById("temas_todos");

       //initialize with all the select boxes hidden except one
       option1.style.cssText='display: none';
       option2.style.cssText='display: none';
       option3.style.cssText='display: none';
       option4.style.cssText='display: none';
       option5.style.cssText='display: none';
       option6.style.cssText='display: none';
       option7.style.cssText='display: none';
       option8.style.cssText='display: none';
       option9.style.cssText='display: none';
       option10.style.cssText='display: none';
       option11.style.cssText='display: none';
       option12.style.cssText='display: none';
       option13.style.cssText='display: block';

  var selectHandler = function() {

     // Show and hide the appropriate select's
     switch(this.value) {
       case "8":
       // Conferências / colóquios
       option1.style.display = "block";
       option2.style.display = "none";
       option3.style.display = "none";
       option4.style.display = "none";
       option5.style.display = "none";
       option6.style.display = "none";
       option7.style.display = "none";
       option8.style.display = "none";
       option9.style.display = "none";
       option10.style.display = "none";
       option11.style.display = "none";
       option12.style.display = "none";
       option13.style.display = "none";
       break;
       case "10":
       // Cursos/workshops
       option1.style.cssText='display: none';
       option2.style.cssText='display: block';
       option3.style.cssText='display: none';
       option4.style.cssText='display: none';
       option5.style.cssText='display: none';
       option6.style.cssText='display: none';
       option7.style.cssText='display: none';
       option8.style.cssText='display: none';
       option9.style.cssText='display: none';
       option10.style.cssText='display: none';
       option11.style.cssText='display: none';
       option12.style.cssText='display: none';
       option13.style.cssText='display: none';
       break;
       case "7":
       // provas
       option1.style.cssText='display: none';
       option2.style.cssText='display: none';
       option3.style.cssText='display: block';
       option4.style.cssText='display: none';
       option5.style.cssText='display: none';
       option6.style.cssText='display: none';
       option7.style.cssText='display: none';
       option8.style.cssText='display: none';
       option9.style.cssText='display: none';
       option10.style.cssText='display: none';
       option11.style.cssText='display: none';
       option12.style.cssText='display: none';
       option13.style.cssText='display: none';
       break;
       case "12":
       // ciencia
       option1.style.cssText='display: none';
       option2.style.cssText='display: none';
       option3.style.cssText='display: none';
       option4.style.cssText='display: none';
       option5.style.cssText='display: block';
       option6.style.cssText='display: none';
       option7.style.cssText='display: none';
       option8.style.cssText='display: none';
       option9.style.cssText='display: none';
       option10.style.cssText='display: none';
       option11.style.cssText='display: none';
       option12.style.cssText='display: none';
       option13.style.cssText='display: none';
       break;

       default:
       // Hide all
       option1.style.cssText='display: none';
       option2.style.cssText='display: none';
       option3.style.cssText='display: none';
       option4.style.cssText='display: none';
        option5.style.cssText='display: none';
       option6.style.cssText='display: none';
       option7.style.cssText='display: none';
       option8.style.cssText='display: none';
       option9.style.cssText='display: none';
       option10.style.cssText='display: none';
       option11.style.cssText='display: none';
       option13.style.cssText='display: block';
     }
  };

  // Use the onchange and onkeypress events to detect when the
  // value of main_select has changed
  attachEvento(main_select, "change", selectHandler);
  attachEvento(main_select, "keypress", selectHandler);
});

Спасибо.

Вот HTML.

      <div class="pesquisa-event-select"><!-- pesquisa select-boxs -->
            <p>
                <label for="tipo">tipo de evento </label>
                <select id="tipos_evento">
                    <option value="104">todos</option>
                    <option value="8">Conferências/Colóquios</option>
                    <option value="10">Cursos/Workshops</option>
                    <option value="7">Provas académicas</option>
                    <option value="9">Visitas/Observações</option>
                    <option value="12">Ciência(outros)</option>
                    <option value="2">Danças</option>
                    <option value="1">Exposições</option>
                    <option value="3">Multidisciplinar</option>
                    <option value="4">Música</option>
                    <option value="5">Teatro</option>
                    <option value="6">Cultura(outros)</option>
                    <option value="48">Desporto</option>
                </select>
            </p>


       <div id="temas_todos">
            <p>
            <label for="Tema">tema de evento </label>
                <select>
                    <option value="">todos</option>
                <xsl:for-each select="temas_todos/TemasEventos/Row">
                    <xsl:sort select="TipoEvento"/>
                    <option value="{Numero}">
                        <xsl:value-of select="TipoEvento" />_
                        <xsl:value-of select="TemaEvento" />
                    </option>
                </xsl:for-each>
                </select>
            </p>
    </div>

    <div id="temas_conferencias">
            <p>
            <label for="Tema">tema de evento</label>
                <select>
                    <option value="">todos</option>
                <xsl:for-each select="temas_conferencias/TemasEventos/Row">
                    <xsl:sort select="TemaEvento"/>
                    <option value="{Numero}">
                        <xsl:value-of select="TemaEvento" />
                    </option>
                </xsl:for-each>
                </select>

            </p>
    </div>

    <div id="temas_cursos">
           <p>
            <label for="Tema">tema de evento</label>
                <select>
                    <option value="">todos</option>
                <xsl:for-each select="temas_cursos/TemasEventos/Row">
                    <xsl:sort select="TemaEvento"/>
                    <option value="{Numero}">
                        <xsl:value-of select="TemaEvento" />
                    </option>
                </xsl:for-each>
                </select>

            </p>
    </div>

Ответы [ 4 ]

0 голосов
/ 07 августа 2009

Проблема в том, что в контексте обратного вызова, назначенного функцией attachEvent (selectHandler), ссылка this не является элементом, затронутым событием, является ссылкой на window объект.

Поскольку вы объявили переменную для хранения ссылки на элемент main_select, вы можете использовать ее в своем выражении switch:

var selectHandler = function() {

    switch(main_select.value) {
    //....
    }
}
0 голосов
/ 07 августа 2009

Не разбивать код, который вы предоставили ... но, вероятно, есть намного более чистый способ реализовать это.(код не проверен)

var attachEvento = function(node, event, listener, useCapture) {
  // Method for FF, Opera, Chrome, Safari
  if (window.addEventListener ) {
     node.addEventListener(event, listener, useCapture || false);
  }
  // IE has its own method
  else {
     node.attachEvent('on'+event, listener);
  }
};

var selectLists = ['temas_conferencias','temas_cursos','temas_provas','temas_visitas','temas_ciencias','temas_dancas','temas_exposicoes','temas_multi','temas_musica','temas_teatro','temas_cultura','temas_desporto','temas_todos'];

var selectHandler = function(){
  var value = this.value;
  var select;
  for(var i=0,sLen=selectLists.length;i<sLen;i++){
     select = document.getElementById(selectLists[i]);
     if(value == (i+1)){
        select.style.display = 'block';
     } else {
        select.style.display = 'none';
     }
  }
};

attachEvento(window, "load", function() {
  // Use the onchange and onkeypress events to detect when the
  // value of main_select has changed
  attachEvento(main_select, "change", selectHandler);
  attachEvento(main_select, "keypress", selectHandler);
});

По сути, он делает это.

  1. Он регистрирует обработчик событий "selectHandler" для событий onchange или onkeypress в главном списке выбора.

  2. Чтобы свести к минимуму код, я поместил идентификаторы «других» списков выбора в массив с именем «selectLists»

  3. Когдасрабатывает selectHandler, он просто проверяет значение основного выбора, затем перебирает другие выборки в массиве «selectLists» и устанавливает отображение на «none» - если только оно не соответствует основному значению выбора, в этом случае он отображает его.

0 голосов
/ 07 августа 2009

сначала очистите код, чтобы сделать его более понятным, и повторите попытку

// Once the window loads and the DOM is ready, attach the event to the main
attachEvento(window, "load", function() {
  var main_select = document.getElementById("tipos_evento");

   var selectOptions = new Array();

   selectOptions.push(document.getElementById("temas_conferencias"));
   selectOptions.push(document.getElementById("temas_cursos"));
   ...
   selectOptions.push(document.getElementById("temas_todos"));

       //initialize with all the select boxes hidden except one
       for (var ind=0; ind< (selectOptions.length-1); ind++)
           selectOptions[ind].style.cssText='display: none';
       selectOptions[13].style.cssText='display: block';


   var selectHandler = function() {

       // Hide all
       for (var ind=0; ind< selectOptions.length; ind++)
           selectOptions[ind].style.cssText='display: none';

     // Show and hide the appropriate select's
     switch(this.value) {
       case "8":
       // Conferências / colóquios
       selectOptions[1].style.display = "block";
       break;
       case "10":
       // Cursos/workshops
       selectOptions[2].style.display='block';
       break;
       case "7":
       // provas
       selectOptions[3].style.display='block';
       break;
       case "12":
       // ciencia
       selectOptions[5].style.display='block';
       break;
       selectOptions[13].style.display='block';
     }
  };

  // Use the onchange and onkeypress events to detect when the
  // value of main_select has changed
  attachEvento(main_select, "change", selectHandler);
  attachEvento(main_select, "keypress", selectHandler);
});
0 голосов
/ 07 августа 2009

Вам также необходимо опубликовать свой HTML, чтобы мы могли точно понять, что происходит не так. Используете ли вы идентификатор, имя или оба, чтобы описать элементы формы? Возможно, вам лучше использовать формат style.display="none" вместо style.cssText, поскольку в последнем случае вы заменяете весь атрибут стиля этого объекта.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...