Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么selectedIndex不';我的代码不工作?_Javascript_Html - Fatal编程技术网

Javascript 为什么selectedIndex不';我的代码不工作?

Javascript 为什么selectedIndex不';我的代码不工作?,javascript,html,Javascript,Html,我有一个简单的例子: <!DOCTYPE html> <html> <body> <select id="mySelect"> <option>Apple</option> <option>Orange</option> <option>Pineapple</option> <option>Banana</option&g

我有一个简单的例子:

<!DOCTYPE html>
<html>
<body>

<select id="mySelect">
  <option>Apple</option>
  <option>Orange</option>
  <option>Pineapple</option>
  <option>Banana</option>
</select>


<script>
document.addEventListener("change", function () {
  var x = document.getElementById("mySelect");
  var y = x.options[x.selectedIndex];
  alert(y);
}
</script>

</body>
</html>
但不能返回给定选项的索引号。当我使用.text而不是.index(从选项获取文本)时,它也不起作用

存在语法问题(缺少
addEventListener
右括号)

document.addEventListener(“更改”,函数(){
var x=document.getElementById(“mySelect”);
变量y=x.options[x.selectedIndex]。索引;
警报(y);
}); // 缺少)此处

苹果
橙色
菠萝
香蕉

要从所选选项访问
文本内容吗?
(因为它的
可直接在select上访问)

事件侦听器也必须用于select,才能使用
this

const mySelect=document.getElementById('my-select'))
mySelect.addEventListener(“更改”,函数()
{
控制台清除()
console.log('value=',this.value',| | content=',this.options[this.selectedIndex].textContent)
})

苹果
橙色
菠萝
香蕉

您应该打开控制台并检查错误。您的代码有不平衡的括号。当我写的时候:
document.addEventListener(“change”,function(){var x=document.getElementById(“mySelect”);var y=x.options[x.selectedIndex].index;alert(y);})
那么不需要在select上使用eventListener,它就可以工作了fine@Muska然后你会得到文档中所有事件的更改,也可以在页面中不属于您选择的其他元素上
var y = x.options[x.selectedIndex].index;