jquery - 当通过jquery按下某个键时如何将样式应用于输入文本

标签 jquery html css

我有一个 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/

相关文章:

javascript - 如何停止在 HTML 中重新加载 jquery

javascript - 如何将网络摄像头或设备捕获的图像存储到站点文件夹?

html - 仅使用 css 将表格从一个位置移动到另一个位置

javascript - jQuery选择器,无法通过

javascript - 获取内容可编辑元素内的选定文本

javascript - 在 chrome/safari 中滚动时背景图像图案表现得很奇怪

jQuery 删除除 anchor 之外的所有 HTML 标签

php - (PHP) 将 'guess counter' 添加到随机数游戏

html - 如何在悬停图像上显示文本

javascript - 基本的 jquery 延迟使用与 ajax