Problem: Javascript's change function is not valid
P粉654894952
2023-09-06 00:04:57
<p>我在使用 JavaScript 更改文本翻译时遇到问题。</p>
<p>这是html代码</p>
<p>
<pre class="brush:js;toolbar:false;">document.getElementById('slider-en1').style.visibility = 'hidden';
document.getElementById('slider-id1').style.visibility = 'visible';
function changeFunc() {
var selectBox = document.getElementById("language_select");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
// alert(selectedValue);
if (selectedValue == 'id') {
document.getElementById('slider-en1').style.visibility = 'visible';
document.getElementById('slider-id1').style.visibility = 'hidden';
}
if (selectedValue == 'en') {
document.getElementById('slider-en1').style.visibility = 'visible';
document.getElementById('slider-id1').style.visibility = 'hidden';
}
}</pre>
<pre class="brush:html;toolbar:false;"><select class="nav-item has-sub-menu language-selector" id="language_select" onchange="changeFunc();">
<ul class="sub-menu">
<li class="nav-item sub-menu-item">
<option class="nav-link sub-menu-link text-white" disabled default selected value="">Language</option>
</li>
<li class="nav-item sub-menu-item">
<option class="nav-link sub-menu-link text-dark" id="id" value="id">Indonesia</option>
</li>
<li class="nav-item sub-menu-item">
<option class="nav-link sub-menu-link text-dark" id="en" value="en">English</option>
</li>
</ul>
</select>
<div class="col-9 col-md-10 col-lg-8 mx-auto" id="slider-id1">
<p class="slide-subtitle narrow-centerd-text">
indonesia indonesia indonesia
</p>
</div>
<div class="col-9 col-md-10 col-lg-8 mx-auto" id="slider-en1">
<p class="slide-subtitle narrow-centerd-text">
en en en
</p>
</div></pre>
</p>
<p>我尝试过使用jquery,但仍然无法正常工作。谢谢您的回答</p>
<p>我尝试使用 JavaScript 显示和隐藏内容,但我的代码无法正常工作</p>
UL LI is not a valid child element of select.
However, I simplified your code for efficiency.
I added a data attribute to each language div. This property holds the language value representing the content. I also created a css class called "active" which will show the appropriate language div and make the language div hidden by default.
Then I used event handler instead of inline event(onchange) which is better way and will also help you to do more in the future.
In my event listener I just get the selected value. I then see if there are any language divs with an active class, and if so, delete it. I then find and add the active class to the appropriate language div.
This process will help you extend your code because you don't need to care about if statements.