[英]Accessing a value from a dropdown menu in Javascript?
So I have a dropdown menu that starts default with no value, so the element looks like this:所以我有一个默认启动的下拉菜单,没有值,所以元素看起来像这样:
<div class="jss213">
<div class="jss214 jss217 jss243 jss228" aria-pressed="false" role="button" aria-haspopup="true" tabindex="0">Basketball
</div>
<input type="hidden" value>
<svg class="jss86 jss219" focusable="false" viewBox="0 0 24 24" aria-hidden="true" role="presentation"><path d="M7 10l5 5 5-5z"></path></svg>
</div>
But when the value is selected, this is how the element looks, with the input value = "Basketball": But when the value is selected, this is how the element looks, with the input value = "Basketball":
<div class="jss213">
<div class="jss214 jss217 jss243 jss228" aria-pressed="false" role="button" aria-haspopup="true" tabindex="0">Basketball
</div>
<input type="hidden" value="Basketball">
<svg class="jss86 jss219" focusable="false" viewBox="0 0 24 24" aria-hidden="true" role="presentation"><path d="M7 10l5 5 5-5z"></path></svg>
</div>
I also get the same output when logging the element with this:使用此记录元素时,我也得到相同的 output :
console.log(root.getElementsByClassName("jss213"))
I'm trying to access the "value" field using this:我正在尝试使用以下方法访问“值”字段:
var serviceName = root.getElementsByClassName("jss213").value
This, however, causes the page to crash with the error "TypeError: Cannot read property 'value' of undefined".但是,这会导致页面崩溃,并显示错误“TypeError: Cannot read property 'value' of undefined”。 Is there a way to check for this value without causing an undefined error?
有没有办法检查这个值而不会导致未定义的错误? Or a way to make sure that the dropdown has properly selected a value before selecting it?
或者在选择之前确保下拉菜单正确选择了一个值的方法?
try using尝试使用
var serviceName = root.querySelector(".jss213 input")?.value
the?这? checks if the element with the class jss213 has an input field with a possible value it either returns "" or the value "basketball" or whatever the value is set to
检查具有 class jss213 的元素是否有一个可能值的输入字段,它返回“”或值“篮球”或任何值设置为
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.