【问题标题】:How to fetch elements from a text box and store them in an array如何从文本框中获取元素并将它们存储在数组中
【发布时间】:2013-01-26 19:12:28
【问题描述】:

谁能帮我将数据存储在从文本框中获取的数组中。我需要设计一种格式,以便在按下空格时它应该在空格字符之前显示不同的字体颜色。并且空格后面的元素应该和往常一样。

编辑:

<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
  var x = 0

  function abc() {
      var a = new Array("a", "b", "c", "d", "e", "f", "g", ..... "h", "x", "y", "z")
      document.getElementById("type").value = a[x]

      var i = document.getElementById("type").value
      var n = i.charAt(i.length - 1)
      alert(n)
      var n = i.substring(0, i.length - 1)
      document.getElementById("type").value = n.concat(a[x]);
      if (x >= 0) x++
      if (x >= 26) x = 0

  }
</script>

</head>
<body>
<!--<input type="text" name="type" id="type" size="100" onkeyup="abc()">-->

<input type="text" name="type" id="type" size="100" onkeypress="abc()">
<div id="log"></div>

另一个尝试:

<script>
  e = jQuery.Event("keypress", {
      keyCode: 32
  });
  jQuery('#type').bind('keydown', function (e) {
      var s = e.which;
      jQuery('#log').html(e.which);

      if (s == 8) { //backspace
          alert('back space');
      }
      if (s == 32) { //space bar
          alert('space');
          var z = document.getElementById("type").value
          jQuery('#type').css({
              'color': 'blue'
          });
      }
  });
</script>
</body>
</html>

【问题讨论】:

  • 您的问题是关于更改输入元素中的文本颜色还是将数据存储在数组中?我看不出这些有什么关系。你能澄清你的问题吗?
  • 不能对输入中的部分文本设置样式,只能设置整个输入的样式。正如@gilly3 所提到的,主题说一件事,问题文本有所不同。请尽量简洁

标签: javascript jquery arrays associative-array


【解决方案1】:

由于您不能在输入中包含多种颜色,因此您应该没有输入,只有一个标签,当用户键入时,您捕获事件并附加到该标签。

$("body").keypress(function (e) {
    var s = e.which;
    var c = String.fromCharCode(e.which);

    $("#log").children(":last").append(document.createTextNode(c));

    if (s == 32)  { // Space
        $("#log").children(":last").css({ 'color': 'blue' });
        $("#log").append($("<span/>"));
    }
});

示例如下:http://jsfiddle.net/B5wwP/

只需单击结果区域并开始输入。我只完成了空格功能,您需要添加其他东西,例如退格...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-13
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    相关资源
    最近更新 更多