所以我的困境是我有一个页面,上面有一个待办事项列表样式输入,带有单选按钮,可以确定要做的事情的优先级。
这是 HTML 部分:
<p style="">A to-do list</p>
<ol class="ch5">
</ol>
<p> </p>
<p>
<label for="txtAdd">New thing to do:</label>
<input name="txtAdd" type="text" id="txtAdd" size="50" maxlength="50"/>
</p>
<p>Set Priority</p>
<p>
<label>
<input type="radio" name="rgPrior" value="hi" id="rgPrior_0"/>
High</label>
<br/>
<label>
<input type="radio" name="rgPrior" value="med" id="rgPrior_1"/>
Meduim</label>
<br/>
<label>
<input type="radio" name="rgPrior" value="low" id="rgPrior_2"/>
Low</label>
<br/>
</p>
<p> </p>
<p>
<input type="button" name="btnAdd" id="btnAdd" value="Add a value" onClick="chapter05()" />
</p>
这是脚本:
var list = document.getElementsByClassName('ch5')[0];
var todo = document.getElementById('txtAdd').value;
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(todo));
list.appendChild(entry);
这是 CSS:
.hiP {
color: red;
}
.medP {
color: blue;
}
.lowP {
color: green;
}
.ch5 {
padding-left: 30px;
}
我一直试图完成的是,如果您在要放入列表的文本框中键入内容并单击优先级单选按钮,则放入列表的任何内容都会显示为红色、蓝色或绿色,具体取决于优先级(红色为高,蓝色为中,绿色为低)。我这辈子都弄不明白。
最佳答案
您可以使用颜色类值创建一个对象,遍历按钮以找到所选的按钮并使用相应的值设置元素颜色:
function chapter05() {
var list = document.getElementsByClassName('ch5')[0];
btn_colors = {
'hi': 'hiP',
'med': 'medP',
'low': 'lowP'
}
radios = document.getElementsByName('rgPrior');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
btn_selected_color = (btn_colors[radios[i].value]);
break;
}
}
var todo = document.getElementById('txtAdd').value;
var entry = document.createElement('li');
entry.className = btn_selected_color;
entry.appendChild(document.createTextNode(todo));
list.appendChild(entry);
}
.hiP {
color: red;
}
.medP {
color: blue;
}
.lowP {
color: green;
}
.ch5 {
padding-left: 30px;
}
<p style="">A to-do list</p>
<ol class="ch5">
</ol>
<p> </p>
<p>
<label for="txtAdd">New thing to do:</label>
<input name="txtAdd" type="text" id="txtAdd" size="50" maxlength="50" />
</p>
<p>Set Priority</p>
<p>
<label>
<input type="radio" name="rgPrior" value="hi" id="rgPrior_0"/>
High</label>
<br/>
<label>
<input type="radio" name="rgPrior" value="med" id="rgPrior_1"/>
Medium</label>
<br/>
<label>
<input type="radio" name="rgPrior" value="low" id="rgPrior_2"/>
Low</label>
<br/>
</p>
<p> </p>
<p>
<input type="button" name="btnAdd" id="btnAdd" value="Add a value" onClick="chapter05()" />
</p>
关于javascript - 单击按钮时设置列表元素的优先级颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46627196/