0

假设我有一个简单的下拉列表,我可以从中自由选择我想要的任何选项。

我可以通过 JavaScript 以这种方式将所选选项的值存储在变量中:

var checkValue = function(){
  const mySelect = document.getElementById("cars");
  let currentValue =  mySelect.options[ mySelect.selectedIndex ].value;
  console.log(currentValue);
}
<select id="cars" onchange="checkValue()">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>

问题:

  1. 如何检查我是否连续两次选择了相同的下拉列表选项,换句话说,如果 的值发生currentValue变化

  2. 使用 AngularJS 会使这项任务更容易吗?如何?

4

3 回答 3

1

您可能正在寻找 onclick 事件,然后检查值是否相同:

var checkValue = function(){
  let mySelect = document.getElementById("cars").options;
  let currentValue =  mySelect[ mySelect.selectedIndex ].value;
  if (currentValue === previousValue) {
    console.log("The same option was selected");
  } else {
    console.log("Different option");
  }
  previousValue = currentValue;
}

let select = document.getElementById("cars").options;
let previousValue = select[select.selectedIndex].value;
<select id="cars">
  <option value="volvo" onclick="checkValue(this)">Volvo</option>
  <option value="saab" onclick="checkValue(this)">Saab</option>
  <option value="opel" onclick="checkValue(this)">Opel</option>
  <option value="audi" onclick="checkValue(this)">Audi</option>
</select>

于 2020-03-06T11:37:07.110 回答
1

var arr = [];
var checkValue = function() {
  const mySelect = document.getElementById("cars");
  let currentValue = mySelect.options[mySelect.selectedIndex].value;

  if ($.inArray(currentValue, arr) != "-1") {
    console.log("already selected");
  } else {
    arr.push(currentValue);
    console.log(currentValue);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<select id="cars" onchange="checkValue()">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>

于 2020-03-06T12:00:51.927 回答
0

连续两次在元素选择上触发事件的示例可能是添加单击事件而不是更改事件,我在考虑MutationObserver但如果它已经选择,则在收听选项更改时似乎不会触发检查here

var activities = document.getElementById("activitySelector");

activities.addEventListener("click", function() {
    console.log('selected item');
});
<select id="activitySelector">
  <option value="addNew">Item</option>
  <option value="1">option 1</option>
</select>

通过点击事件,您可以这样做:

let selectedoptions = [];
var clickListener = function(){
  const mySelect = document.getElementById("cars");
  let currentValue =  mySelect.options[ mySelect.selectedIndex ].value;
  if(selectedoptions.indexOf(currentValue) < 0) {
    selectedoptions.push(currentValue);
  }
  else {
    console.log('selected before');
  }
  //console.log(currentValue);
}
<select id="cars" onclick="clickListener()">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>

于 2020-03-06T11:57:04.157 回答