在Selector-JavaScript中更改选项后更改段落文本
我试图让我的段落根据选择的选项进行更新,而不使用提交按钮。因此,我目前正试图通过在Selector-JavaScript中更改选项后更改段落文本,javascript,Javascript,我试图让我的段落根据选择的选项进行更新,而不使用提交按钮。因此,我目前正试图通过onchange事件来实现这一点。但我什么也做不到,有人知道我哪里做错了吗 函数选择器(){ document.getElementById(“p”).innerHTML='您当前选择了“红色!”; } 函数selectG(){ document.getElementById(“p”).innerHTML='您当前选择了“绿色”; } 函数selectB(){ document.getElementById(“p”
onchange
事件来实现这一点。但我什么也做不到,有人知道我哪里做错了吗
函数选择器(){
document.getElementById(“p”).innerHTML='您当前选择了“红色!”;
}
函数selectG(){
document.getElementById(“p”).innerHTML='您当前选择了“绿色”;
}
函数selectB(){
document.getElementById(“p”).innerHTML='您当前选择了“蓝色”;
}
红色
绿色
蓝色
您当前选择了“红色”!
//向select添加一个id值,将函数调用设置为select onchange事件
红色
绿色
蓝色
函数selectChange(){
//抓住你的选择元素
const selectElement=document.getElementById('ddlMySelect');
//获取所选选项的文本值
const selectedText=selectElement.options[selectElement.selectedIndex].text;
//逻辑改变你的段落文本,这实际上是过度杀戮
//只需将文本替换为选项文本,请参见下面的注释
document.getElementById(“p”).innerHTML='您当前有'+selectedText+'Selected!'';
}
所选函数(){
var index=document.getElementById(“mySelect”).selectedIndex;
开关(索引){
案例0:
document.getElementById(“p”).innerHTML='您当前选择了“红色!”;
打破
案例1:
document.getElementById(“p”).innerHTML='您当前选择了“绿色”;
打破
案例2:
document.getElementById(“p”).innerHTML='您当前选择了“蓝色”;
打破
}
}
红色
绿色
蓝色
您当前选择了“红色”!
一种非常简单的方法:
函数onChangeSelectColor(){
var colorValue=document.getElementById(“colorSelect”);
var colorIndex=colorValue.options[colorValue.selectedIndex].value;
var colorMessage='';
如果(colorIndex==1)
colorMessage='您当前选择了“红色!”;
else if(colorIndex==2)
colorMessage='您当前选择了“绿色!”;
else if(colorIndex==3)
colorMessage='您当前选择了“蓝色!”;
document.getElementById(“p”).innerHTML=colorMessage;
}
红色
绿色
蓝色
您当前选择了“红色”
您还可以以动态方式构建它,这样您甚至不必担心if和else。大概是这样的:
var select=document.getElementById('select'),
color=document.getElementById('color');
select.addEventListener('change',function()){
var selected=this.options[this.selectedIndex].value;
color.innerHTML=已选择;
});代码>
颜色
红色
绿色
蓝色
您当前已选择
我认为事件是在选择
上触发的,而不是选项
,但我不确定……将onchange事件放在select元素上,当它触发时,获取所选选项并更改您的innerHTML@MattHutch我在下面为您添加了一个答案。虽然此解决方案可行,如果您在下拉列表中添加或删除选项,这可能不起作用,因为您正在使用颜色对索引进行硬编码。我认为检查所选选项的文本是一个更好的解决方案。我认为最好的方法是为每个选项添加一个值并使用该值。虽然此解决方案可行,但如果您在下拉列表中添加或删除选项,这可能不起作用,因为您正在使用颜色硬编码索引。我相信检查所选选项的文本是一个更好的解决方案@RyanWilson这是一个非常公平的观点,我已经更新了我的代码,以反映我的搜索选项中的值。
//Add an id value to your select, set the function call to the select onchange event
<select id="ddlMySelect" onchange="selectChange();">
<option>Red</option>
<option>Green</option>
<option>Blue</option>
</select>
function selectChange() {
// Grab your select element
const selectElement = document.getElementById('ddlMySelect');
// Get the text value of the selected option
const selectedText = selectElement.options[selectElement.selectedIndex].text;
// Logic to change your paragraph text, this is actually over kill
// Just replace the text with the option text, see below comments
document.getElementById("p").innerHTML = 'You Currently Have ' + selectedText + ' Selected!';
}