纯JavaScript。 Chrome。
html
<select name="your-course" class="wpcf7-form-control wpcf7-select wpcf7-validates-as-required" id="course-selection" aria-required="true" aria-invalid="false">
<option value="">---</option>
<option value="makeup">Make up</option>
<option value="hairdress">Hairdress</option>
<option value="tatoo">Tatoo</option>
</select>
<input type="submit" value="Submit" class="wpcf7-form-control wpcf7-submit" id="contact-submit" /></p>
然后在浏览器中选择某项。说,理发。并转到控制台。它在Chrome中。但这必须适用于所有浏览器。
var sel = document.getElementById("course-selection")
现在,我可以检查是否已找到sel。然后。
sel.selectedIndex
结果为0。始终为0。无论我选择什么。这个问题似乎在互联网上经常讨论。好吧,我也在这里炸了。
你能踢我一脚吗?
答案 0 :(得分:1)
可能您正在尝试获取selectedIndex
之前的更改吗?
尝试进行此操作onchange
(请参见下面的代码段):
var sel = document.getElementById("course-selection")
sel.onchange = function() {
console.log(sel.selectedIndex);
}
<select name="your-course" class="wpcf7-form-control wpcf7-select wpcf7-validates-as-required" id="course-selection" aria-required="true" aria-invalid="false">
<option value="">---</option>
<option value="makeup">Make up</option>
<option value="hairdress">Hairdress</option>
<option value="tatoo">Tatoo</option>
</select>
答案 1 :(得分:0)
可能,您可能会在某些jspfiddle
或codepen
或某些在线编辑器中进行此操作,如果是,通常情况下,您的方法不会之所以有效,是因为它们大多数都使用html渲染框架,因此chrome控制台试图在父窗口中找到您选择的内容,但是它在子框架中
让我证明您的代码通常可以正常工作:
const el = document.getElementById("course-selection");
console.log(el.selectedIndex) // 0
el.value = 'makeup'
console.log(el.selectedIndex) // 1
el.value = 'hairdress'
console.log(el.selectedIndex) // 2
el.value = 'tatoo'
console.log(el.selectedIndex) // 3
el.addEventListener('change', (e) => {console.log('onchange by user:', e.target.selectedIndex)}) // this is also working
<select name="your-course" class="wpcf7-form-control wpcf7-select wpcf7-validates-as-required" id="course-selection" aria-required="true" aria-invalid="false">
<option value="">---</option>
<option value="makeup">Make up</option>
<option value="hairdress">Hairdress</option>
<option value="tatoo">Tatoo</option>
</select>
<input type="submit" value="Submit" class="wpcf7-form-control wpcf7-submit" id="contact-submit" /></p>