当我运行 $('#myId').val()
时,我有一个元素返回 true
或 false
值>。
一旦返回 true 或 false,我希望将特定的 div
的背景颜色更改为绿色(表示 true)或红色(表示 false)。
if ($('#myId').val())
{
code should return a div with text and green background
}
else
{
code should return a div with text and red background
}
最佳答案
您必须将字符串转换为 bool 值才能正确计算。我的 fiddle 中有一个按钮可以返回值。
HTML:
<div id="myDiv">
<input id="myID" value="false"/>
<input id="myBtn" type="button" value="submit"/>
</div>
JQuery:
$('#myBtn').on('click', function () {
$('#myDiv').css('background', (($('#myID').val() == "true") ? 'green' : 'red'));
});
关于javascript - 使用 jQuery 响应 HTML 元素来更改 DIV 的背景和文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16216985/