Изменить Div Class в зависимости от значения в опции выбора - PullRequest
0 голосов
/ 11 января 2020

У меня есть выпадающий список с опциями, и я хочу, чтобы отображал определенный div в зависимости от выбора в выпадающем меню.

Технически, я считаю, что самый простой способ - установить div, которые не должны быть видны только для display: none , применяя правильный css класс.

Однако я не знаю, как создать соответствующий код JS / jQuery. Я рассматривал здесь другие решения за последние полчаса, но они были более уникальными для их проблемы, хотя я верю, что мое решение может быть очень простым.

Может кто-нибудь помочь мне?

Большое спасибо !!

Лучший, Дэвид

$(document).ready(function () {
    $("#LooseTea").hide();
    $('#PyramidBags').show();
    $('#ProductSelect-product-template-option-0').change(function () {
        if($("#ProductSelect-product-template-option-0").val()=="Loose Tea")
        {
          $("#LooseTea").show();
          $("#PyramidBags").hide();
        }
        else
        {      
          $("#PyramidBags").show();
          $("#LooseTea").hide();
        }
    })
});
<select id="ProductSelect-product-template-option-0">
  <option value="Pyramid Bags">Praymid Bags</option>
  <option value="Loose Tea">Loose Tea</option>
</select>

<div class="">
  <p>This text is about the first product</p>
</div>

<div class="">
  <p>This textis about the second product</p>
</div>

Ответы [ 4 ]

1 голос
/ 11 января 2020

Я считаю, что лучше использовать один div для отображения текстов в соответствии с выбранным параметром. Сохраняйте все сообщения о вашем продукте в массиве в том порядке, в котором он размещен в элементе select, и используйте метод selectedIndex(), чтобы получить индекс выбранной опции, который, в свою очередь, будет использоваться для получения соответствующего текста в массив. Таким образом, если у вас есть сотни продуктов, вам не понадобятся сотни элементов DOM только для отображения информации о продукте.

const selectElement = document.getElementById('productselection'); 
const divElement = document.getElementById('product'); 
const aboutProducts = ['This text is about product one', 'This text is about product two'];
function changeText() {
  let text = aboutProducts[selectElement.selectedIndex];
  divElement.innerHTML = text;
}
<select id="productselection" onchange="changeText()">
  <option value="PyramidBags">Praymid Bags</option>
  <option value="LooseTea">Loose Tea</option>
</select>

<div class="">
  <p id = 'product'>This text is about product one</p>
</div>
1 голос
/ 11 января 2020

Добавьте идентификаторы в Div для лучшего понимания

<select id="productselection">
  <option value="Pyramid Bags">Praymid Bags</option>
  <option value="Loose Tea">Loose Tea</option>
</select>

<div id='product1' class="">
 <p>This text is about the first product</p>
</div>

<div id='product2' class="">
 <p>This text is about the second product</p>
</div>

Вместо того, чтобы делать так много кода, вы можете легко сделать вот так

 $(document).ready(function () {
   $("#product2").hide();
  });

 $("#productselection").change(function() {
    if($('#PyramidBags').val()=='Pyramid Bags')
  { 

     $("#product1 p").css('color', 'red');
  }
   else
  { 
    $("#product2").show();
    $("#product2 p").css('color', 'green');
  }

});
1 голос
/ 11 января 2020

Вот тебе go!

var product1 = document.getElementById("product1");
var product2 = document.getElementById("product2");
var productselection = document.getElementById("productselection");

productselection.addEventListener("change", function(){
  if(productselection.value === 'PyramidBags'){
    product1.classList.add('CLASS');
    if(product2.classList.contains('CLASS')){
      product2.classList.remove('CLASS');
    }
  }
  if(productselection.value === 'LooseTea'){
    product2.classList.add('CLASS');
    if(product1.classList.contains('CLASS')){
      product1.classList.remove('CLASS');
    }
  }
});
.CLASS{
  color:red
}
<select id="productselection">
  <option value="PyramidBags">Praymid Bags</option>
  <option value="LooseTea">Loose Tea</option>
</select>

<div id='product1' class="CLASS">
  <p>This text is about the first product</p>
</div>

<div id='product2' class="">
  <p>This text is about the second product</p>
</div>

Также это может помочь Как изменить класс элемента с помощью JavaScript?

Ответ на комментарий ОП.

var product1 = document.getElementById("product1");
var product2 = document.getElementById("product2");
var productselection = document.getElementById("productselection");

productselection.addEventListener("change", function(){
    if(productselection.value == 'PyramidBags'){
        if(product1.style.display !== 'block'){
            product1.style.display = 'block';
            product2.style.display = 'none';
        }
    }
    if(productselection.value == 'LooseTea'){
        if(product2.style.display !== 'block'){
            product2.style.display = 'block';
            product1.style.display = 'none';
        }
    }
});
<select id="productselection">
  <option value="PyramidBags">Praymid Bags</option>
  <option value="LooseTea">Loose Tea</option>
</select>

<div id='product1'>
  <p>This text is about the first product</p>
</div>

<div id='product2' style='display:none'>
  <p>This text is about the second product</p>
</div>

Кроме того, использование jQuery делает все проще.

0 голосов
/ 11 января 2020

document.getElementById("productselection").onchange = (e) => {
    let dataId = e.target.options[e.target.selectedIndex].dataset.id
    
    document.querySelectorAll(".txt").forEach(el => {
        el.style.display = el.dataset.id === dataId ? "block" : "none"
    })
}
.txt{display: none}
<select id="productselection" name="a">
  <option value="PyramidBags" data-id="pr-1">Pyramid Bags</option>
  <option value="LooseTea" data-id="pr-2">Loose Tea</option>
</select>

<div class="txt" data-id="pr-1">
  <p>This text is about the first product</p>
</div>

<div class="txt" data-id="pr-2">
  <p>This textis about the second product</p>
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...