我有一个 div,用户在其中输入用逗号分隔的电子邮件 ID,我想在输入有效电子邮件时将它们着色为 background-color:green
并且用户为下一个电子邮件地址输入逗号,虽然我的函数是在按逗号时调用的,但我仍然坚持应用它,但我无法通过 jquery 在 css 中应用样式
这是我的代码
$('.team-btn').click(function() {
$('.team-intro').replaceWith($(".team-invite").clone().show());
$('#invite-emails').keydown(function(event) {
if (event.keyCode === 188) {
$val = $(this).val();
$(this).val.apply("<span style='background-color:green'>");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="team-intro">
<p>XXXX is a Free to use, Invite your team and get started today</p>
<button class="team-btn">Invite Now</button>
</div>
<div class="team-invite" style="display:none;">
<p>Enter emails and we will invite your mates to join you.</p>
<input type="text" id='invite-emails' name='email' placeholder='enter emails here' size="30">
<br>
<!--<div data-value="" id='style-email' style="padding-left: 12px; padding-right: 12px;">-->
<p id='subtext'>You can enter multiple emails with comma</p>
</div>
最佳答案
您不能对 val()
函数“应用”任何内容。您也不能在 input
的值内添加 HTML 并让渲染器解释它。
要设置元素的样式,您最好添加/删除预定义的 CSS 类。试试这个:
$('.team-btn').click(function() {
$('.team-intro').replaceWith($(".team-invite").clone().show());
$('#invite-emails').keydown(function(event) {
if (event.keyCode === 188) {
$(this).addClass('foo');
}
});
});
.foo { background-color: #0C0; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="team-intro">
<p>XXXX is a Free to use, Invite your team and get started today</p>
<button class="team-btn">Invite Now</button>
</div>
<div class="team-invite" style="display:none;">
<p>Enter emails and we will invite your mates to join you.</p>
<input type="text" id='invite-emails' name='email' placeholder='enter emails here' size="30">
<br>
<!--<div data-value="" id='style-email' style="padding-left: 12px; padding-right: 12px;">-->
<p id='subtext'>You can enter multiple emails with comma</p>
</div>
关于jquery - 当通过jquery按下某个键时如何将样式应用于输入文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43973762/