jquery:如何循环遍历在textarea中键入的每一行换行文本?
比如说,在一个jquery:如何循环遍历在textarea中键入的每一行换行文本?,jquery,Jquery,比如说,在一个中,我在每一行上键入一组关键字 keyword1 keyword2 keyword3 ... $('textarea[name=sometextarea]').val().split('\n').each(function(e){ alert($(this)); }); 我认为您的问题在于jquery对象。val()返回一个字符串,split()将返回一个数组。但是each()是JQuery对象的一个属性。请尝试以下方法: $($('te
中,我在每一行上键入一组关键字
keyword1
keyword2
keyword3
...
$('textarea[name=sometextarea]').val().split('\n').each(function(e){
alert($(this));
});
我认为您的问题在于jquery对象。val()返回一个字符串,split()将返回一个数组。但是each()是JQuery对象的一个属性。请尝试以下方法:
$($('textarea[name=sometextarea]').val().split('\n')).each(function(e){
alert($(this));
});
请注意split()返回值周围额外的$(…)。数组对象没有任何
方法。在循环字符串而不是元素时,请使用jQuery.each
方法(而不是jQuery().each方法):
像这样
$.each($('textarea[name=sometextarea]').val().split('\n'), function(e){
alert(this);
});
jQuery在jQuery
(或$
)对象上提供了一个每个方法。应使用此选项,而不是从数组中创建jQuery对象:
$.each($('textarea[name=sometextarea]').val().split('\n'), function(e){
alert(this);
});
如果我有一个文本区域,它有一定的宽度,并且输入了文本,由于文本区域的结尾,文本自动转到新行,那么该字符串可以被拆分为每行新字符串吗?我已经用codeigniter和php解决了这个问题。
下面是一个代码:
$this->load->helper('text');
$name = 'some text that is longer than the width of text area and you need to do some thing with it...';
$name_array = word_wrap($name, 20); //20 is a number of character where your text will be wrapped.
foreach(preg_split("/((\r?\n)|(\r\n?))/", $name_array) as $line){
echo $line.'</br>';
//from here, you can do what ever you want with $line, put it to another array..whatever
}
$this->load->helper('text');
$name='某些文本长度超过文本区域的宽度,您需要对其进行处理…';
$name\u array=word\u wrap($name,20)//20是文本将被包装的字符数。
foreach(preg_split(“/(\r?\n)|(\r\n?)/”,$name_数组)作为$line){
回显$line.“”;
//从这里,你可以用$line做任何你想做的事情,把它放到另一个数组中……随便什么
}
$(“#您的文本区域”).live(“按键”,函数(){
变量行=$(this.val().split(“\n”);
$。每个(行,函数(n,元素){
控制台日志(elem);
$(“”).text(elem).appendTo($(“#target”);
});
您可以使用live on keypress“侦听”,正如其他人建议的那样,按换行符拆分,循环中的技巧是使用“each”可以得到一个索引和值(代码中的元素)。此代码段将行值附加到另一个目标元素,您可以在使用
$(“#target”).empty();$()。each()方法用于迭代元素,而$方法用于迭代其他对象,如字符串数组。建议each()方法用于迭代其他对象。这将返回[Object Object],而不是字符串。我尝试了此.text(),它表示没有方法错误。它表示此.text()不是函数。@aoghq:jQuery出于某种原因将值强制转换为对象。您可以使用字符串(this)将值强制转换回字符串。
$this->load->helper('text');
$name = 'some text that is longer than the width of text area and you need to do some thing with it...';
$name_array = word_wrap($name, 20); //20 is a number of character where your text will be wrapped.
foreach(preg_split("/((\r?\n)|(\r\n?))/", $name_array) as $line){
echo $line.'</br>';
//from here, you can do what ever you want with $line, put it to another array..whatever
}
$("#your-text-area").live("keypress",function(){
var lines = $(this).val().split("\n");
$.each(lines, function(n, elem) {
console.log(elem);
$("<li></li>").text(elem).appendTo($("#target"));
});