![](/img/trans.png)
[英]Within a div containing both text and an HTML element, how to change only the text and not the element, using JQuery?
[英]Responding to an HTML element to change background and text of a DIV using jQuery
我有一個在運行$('#myId').val()
時返回true
或false
值的元素。
一旦返回true或false,我想讓特定的div
將其背景顏色更改為綠色(代表真)或紅色(代表假)。
if ($('#myId').val())
{
code should return a div with text and green background
}
else
{
code should return a div with text and red background
}
我會說做一個默認的綠色背景類,然后我們給一個重寫類添加紅色背景。 您的代碼如下所示:
if ($('myId').val())
{
$('myId').addClass('falseClass');
} else {
$('myId').removeClass('falseClass');
};
使用CSS添加背景顏色,如下所示:
.divClass{
background: green;
}
.divClass.falseClass{
background: red;
}
如果要添加帶有某些特定文本的div(例如對任何“ myId”標記進行更改),然后更改顏色,則可以先添加div。
$('<div class="divClass">').appendTo('myId').text('foo')
if ($('myId').val())
{
$('myId').addClass('falseClass');
} else {
$('myId').removeClass('falseClass');
};
您必須將字符串轉換為布爾值才能正確評估。 我在提琴中有一個按鈕可以返回值。
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'));
});
<script type="text/javascript">
if ($('#myId').val()){
showDiv("green");
}else{
showDiv("red");
}
function showDiv(color){
var text = "Hello world";
return "<div class=\""+color+"\">"+text+"</div>";
}
</script>
<style>
.green{
background-color:green;
}
.red{
background-color:red;
}
</style>
這對我來說最有效:
if ($('#myID').val()) {
$('#SOMECLASS').text('Some Text').css('background-color', 'green');
else
$('#SOMECLASS').text('Some Text').css('background-color', 'red');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.