11

html

<textarea id="gps" name="gps"></textarea>
<button>Click</button>

jQuery

$('button').click(function(){
    var arrayOfLines = $('#gps').val().split('\n');
    $.each(arrayOfLines, function(index, item) {
        $this = $(this);
        console.log($this);         
    });
});

我正在尝试单独输出每一行,以便以后可以使用它们,但目前上面似乎分割了每一行,然后将每个字母作为一个对象

JSBin

4

4 回答 4

16

您正在将字符串放入 jQuery 对象中。只需使用item

$('button').click(() => {
  var arrayOfLines = $('#gps').val().split('\n');
  arrayOfLines.forEach(item => console.log(item));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<textarea id="gps" name="gps">28.73514, -147.42323
4.09974, 66.93197
49.11390, 48.85446</textarea>
<button>Click</button>

于 2013-11-08T11:50:00.260 回答
1

在 .each 循环行 id 'item' 对象内,而不是 'this'。

<textarea id="gps" name="gps"></textarea>
  <button id="btn">Click</button>
  $('#btn').click(function(){
      var arrayOfLines = $('#gps').val().split('\n');
      $.each(arrayOfLines, function(index, item) {
          console.log('here is line:', item);         
      });
  });
于 2013-11-08T11:55:57.963 回答
0

你没有正确处理“这个”。尝试以下操作:

$('button').click(function(){
  var arrayOfLines = $('#gps').val().split('\n');
  $.each(arrayOfLines, function(index, item) {
    console.log(this);
  });
});

请注意,我相信内部函数中的“this”变量以换行符开头。但这应该让你走上正轨。

于 2013-11-08T11:52:58.407 回答
0

我认为您不能以这种方式使用 html 标签,为此您必须为每个标签指定和 ID,然后在 jQuery 函数中访问。

 <textarea id="gps" name="gps"></textarea>
<button id="btn">Click</button>
$('#btn').click(function(){
    var arrayOfLines = $('#gps').val().split('\n');
    $.each(arrayOfLines, function(index, item) {
        $this = $(this);
        console.log($this);         
    });
});
于 2013-11-08T11:53:02.347 回答