【问题标题】:set option in a custom select in javascript [closed]在javascript中的自定义选择中设置选项[关闭]
【发布时间】:2021-04-12 08:15:15
【问题描述】:

html、css和js部分在这个链接here.

问题:

这是一个电子桌面应用程序。

我想从数据库中检索一些数据并显示在窗口中。

我不知道如何在不点击 gui 的情况下设置自定义选择。

我需要从 JavaScript 本身设置选项。

感谢任何帮助。谢谢

【问题讨论】:

  • 你的意思是你需要通过数据库来提供你的下拉菜单,还是你需要使用 js 从下拉菜单中动态设置默认选择?我无法识别您的问题目标,
  • 我需要使用从数据库中检索到的数据设置一个选项。我成功地检索了数据。我无法找到将选项设置为选择的方法。 @BurhamB.Soliman
  • 您需要为每个选择设置一个事件,因此当用户选择一个项目时,您希望它显示结果,如果您的意思是这样,您需要将onchange 事件添加到您的选择标签,例如:<select id="selectionchange" onchange="changefunc()"> 并使用 javascript 添加一个函数来完成您的工作,<script> function changefunc() { var selection = document.getElementById("selectionchange").value; // use anyaction you need with the variable named 'selection' } </script>
  • 我试过用它。但它与现有的 js 分类,并且根本不呈现选择。请帮忙。 @BurhamB.Soliman
  • 所有必要的信息都应该在问题中。请参阅site guidelines 了解更多信息。

标签: javascript html electron


【解决方案1】:

您需要以编程方式将选项添加到现有选择器。考虑以下几点:

<select id="mySelector"></select>

假设您的电子应用程序模板中有上述内容。从数据库接收数据后,动态创建每个选项并附加到此选择器:

const data = [ { name: 'Option1', value: 'value1' }, { name: 'Option2', value: 'value2' } ]; // assuming the data is an array of objects
const sel = document.getElementById('mySelector');
data.forEach(opt => {
    const option = document.createElement('option');
    option.setAttribute('value', opt.value);
    option.innerHTML = opt.name;
    sel.appendChild(option);
});

生成的输出应该如下:

<select id="mySelector">
    <option value="value1">Option1</option>
    <option value="value2">Option2</option>
</select>

希望能帮助您了解如何使用 JavaScript 向页面动态添加内容。

编辑

要选择一个选项,只需将selected 属性添加到该选项:

option.setAttribute('selected', true);

编辑 2

在简要查看您的代码(特别是 js/expense.js)后,我可以看到您实际上是在创建一个 div 元素并尝试模拟选项元素的功能。在这种情况下,设置selected 属性将不起作用。由于您是自己创建此 div,因此您可以通过多种方式将任何选项 div 标记为选中。例如,您可以在每个选项 div 上侦听 click 事件,然后分配一个数据属性以将其标记为选中。根据您的代码:

a.addEventListener('click', (e) => e.currentTarget.setAttribute('data-selected', 'true'));

上面的 sn-p 假设 a 是您使用 document.createElement('div') 创建的 div 元素。 sn-p 添加一个click 处理程序,单击时只需在选项上添加一个数据属性。现在您应该添加其他检查以确保从其他选项中删除 data-selected 属性,以防用户稍后更改选项。

最后,要查找选择的选项,您可以尝试以下操作:

const selected = document.querySelector("div[data-selected='true']");

注意:data-selected 的值是字符串而不是布尔值。因此,您可以添加任何计算结果为 true 的值来指示选择。

【讨论】:

  • 不,我不想动态添加选项列表。我只需要显示一个选项作为选定的选项。我试过 option.setAttribute('selected', true);它不工作。请问你能帮我吗? @Abrar
  • 请分享您的代码。你的问题不够清楚,我为额外的细节道歉。我之前使用过 setAttribute 并且它没有问题,所以没有查看您的代码,我无法进一步评论
  • 这是github链接。请看一看。 github.com/sankarsubramaniankvs/wallet-electron
  • 您的代码抛出错误“TypeError:无法在 'Node' 上执行 'appendChild':参数 1 不是 'Node' 类型。”更改 sel.appendChild(opt);到 sel.appendChild(option);在第二个代码块
  • @Ivandez 我修复了错误。
【解决方案2】:

据我了解,您需要进行选择操作,因此我在 if selected 语句中添加了所需的操作

if (elmnt == y[i]) {
      arrNo.push(i)
        document.getElementById("result").innerHTML = "You selected: " + y[i].innerHTML;
    } else {
      y[i].classList.remove("select-arrow-active");
    }

检查sn-p

var x, i, j, l, ll, selElmnt, a, b, c;
/*look for any elements with the class "custom-select":*/
x = document.getElementsByClassName("custom-select");
l = x.length;
for (i = 0; i < l; i++) {
  selElmnt = x[i].getElementsByTagName("select")[0];
  ll = selElmnt.length;
  /*for each element, create a new DIV that will act as the selected item:*/
  a = document.createElement("DIV");
  a.setAttribute("class", "select-selected");
  a.innerHTML = selElmnt.options[selElmnt.selectedIndex].innerHTML;
  x[i].appendChild(a);
  /*for each element, create a new DIV that will contain the option list:*/
  b = document.createElement("DIV");
  b.setAttribute("class", "select-items select-hide");
  for (j = 1; j < ll; j++) {
    /*for each option in the original select element,
    create a new DIV that will act as an option item:*/
    c = document.createElement("DIV");
    c.innerHTML = selElmnt.options[j].innerHTML;
    c.addEventListener("click", function(e) {
        /*when an item is clicked, update the original select box,
        and the selected item:*/
        var y, i, k, s, h, sl, yl;
        s = this.parentNode.parentNode.getElementsByTagName("select")[0];
        sl = s.length;
        h = this.parentNode.previousSibling;
        for (i = 0; i < sl; i++) {
          if (s.options[i].innerHTML == this.innerHTML) {
            s.selectedIndex = i;
            h.innerHTML = this.innerHTML;
            y = this.parentNode.getElementsByClassName("same-as-selected");
            yl = y.length;
            for (k = 0; k < yl; k++) {
              y[k].removeAttribute("class");
            }
            this.setAttribute("class", "same-as-selected");
            break;
          }
        }
        h.click();
    });
    b.appendChild(c);
  }
  x[i].appendChild(b);
  a.addEventListener("click", function(e) {
      /*when the select box is clicked, close any other select boxes,
      and open/close the current select box:*/
      e.stopPropagation();
      closeAllSelect(this);
      this.nextSibling.classList.toggle("select-hide");
      this.classList.toggle("select-arrow-active");
    });
}
function closeAllSelect(elmnt) {
  /*a function that will close all select boxes in the document,
  except the current select box:*/
  var x, y, i, xl, yl, arrNo = [];
  x = document.getElementsByClassName("select-items");
  y = document.getElementsByClassName("select-selected");

  xl = x.length;
  yl = y.length;
  for (i = 0; i < yl; i++) {
    if (elmnt == y[i]) {
      arrNo.push(i)
        document.getElementById("result").innerHTML = "You selected: " + y[i].innerHTML;
    } else {
      y[i].classList.remove("select-arrow-active");
    }
  }
  for (i = 0; i < xl; i++) {
    if (arrNo.indexOf(i)) {
      x[i].classList.add("select-hide");
    }
  }
}
/*if the user clicks anywhere outside the select box,
then close all select boxes:*/
document.addEventListener("click", closeAllSelect);
/*the container must be positioned relative:*/
.custom-select {
  position: relative;
  font-family: Arial;
}

.custom-select select {
  display: none; /*hide original SELECT element:*/
}

.select-selected {
  background-color: DodgerBlue;
}

/*style the arrow inside the select element:*/
.select-selected:after {
  position: absolute;
  content: "";
  top: 14px;
  right: 10px;
  width: 0;
  height: 0;
  border: 6px solid transparent;
  border-color: #fff transparent transparent transparent;
}

/*point the arrow upwards when the select box is open (active):*/
.select-selected.select-arrow-active:after {
  border-color: transparent transparent #fff transparent;
  top: 7px;
}

/*style the items (options), including the selected item:*/
.select-items div,.select-selected {
  color: #ffffff;
  padding: 8px 16px;
  border: 1px solid transparent;
  border-color: transparent transparent rgba(0, 0, 0, 0.1) transparent;
  cursor: pointer;
  user-select: none;
}

/*style items (options):*/
.select-items {
  position: absolute;
  background-color: DodgerBlue;
  top: 100%;
  left: 0;
  right: 0;
  z-index: 99;
}

/*hide the items when the select box is closed:*/
.select-hide {
  display: none;
}

.select-items div:hover, .same-as-selected {
  background-color: rgba(0, 0, 0, 0.1);
}
<div class="custom-select" style="width:200px;">
  <select id="selectone" onchange="selectfunc()">
    <option value="0">Select car:</option>
    <option value="1">Audi</option>
    <option value="2">BMW</option>
    <option value="3">Citroen</option>
    <option value="4">Ford</option>
    <option value="5">Honda</option>
    <option value="6">Jaguar</option>
    <option value="7">Land Rover</option>
    <option value="8">Mercedes</option>
    <option value="9">Mini</option>
    <option value="10">Nissan</option>
    <option value="11">Toyota</option>
    <option value="12">Volvo</option>
  </select>
</div>
<div id="result"></div>

【讨论】:

  • 不,我有一个窗口来检索数据并显示它。用户已经选择了数据,并将其作为记录存储在数据库中。现在我需要在新窗口中显示它(有点像在 gui 中浏览数据库)。在我检索数据后,我需要设置它。 @伯勒姆
  • 您可以将操作更改为您想要的,我只是在提示您如何获得结果,因此您需要将输出语句更改为您自己的,这是我以前习惯的显示结果,您可以使用相同的变量 y[i].innerHTML 将 document.getElementById("result").innerHTML = "You selected: " + y[i].innerHTML; 替换为您的代码
猜你喜欢
  • 2020-09-09
  • 1970-01-01
  • 1970-01-01
  • 2011-08-04
  • 1970-01-01
  • 1970-01-01
  • 2016-10-01
  • 2019-03-17
  • 2010-11-20
相关资源
最近更新 更多