<!--- for loop that i have tried --->
<script >
var something = $('textarea[id^="alllthedesc"]');
$(something).each(function () {
var innervalue = $(this).val();
if (innervalue.length > 0) {
return innervalue
};
});
console.log(innervalue); <
</script>
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> //textarea
<!--- textarea --->
<div class="container">
<textarea name="alllthedesc1" id="alllthedesc1">
this is some text for the first one </textarea>
<textarea name="alllthedesc2" id="alllthedes2">
this is some text for number 2 </textarea>
<textarea name="alllthedesc3" id="alllthedesc3">
this is some text for the number 3 </textarea>
</div>
&#13;
我有以下文本区域结构,必须将其放入一个数组中,然后用于警报,即警报将通过循环并显示满足某个条件的每条文本消息。我尝试了一个for循环,但for循环没有返回我想要的值。 以下是我的尝试
<!--- bootstrap --->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> //textarea
<!--- textarea --->
<div class="container">
<textarea name="alllthedesc1" id="alllthedesc1">
this is some text for the first one </textarea>
<textarea name="alllthedesc2" id="alllthedes2">
this is some text for number 2 </textarea>
<textarea name="alllthedesc3" id="alllthedesc3">
this is some text for the number 3 </textarea>
</div>
<!--- for loop that i have tried --->
<script >
var something = $('textarea[id^="alllthedesc"]');
$(something).each(function () {
var innervalue = $(this).val();
if (innervalue.length > 0) {
return innervalue
};
});
console.log(innervalue); <
</script>
<!--- Jquery --->
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" > </script>
答案 0 :(得分:1)
只需使用map()方法而不是each()方法,这样就可以从迭代中返回值。
var something = $('textarea[id^="alllthedesc"]');
//you need to use map() instead of each() method because each() does not return any value
var innervalue = something.map(function() {
if ($(this).val().length > 0){return $(this).val()};
}); // in innervalue you will get all the values
答案 1 :(得分:1)
您已声明变量&#39; var innervalue&#39;在循环内部并在循环外使用它。如果要在外部使用它,请在循环外声明变量,如下所示。
var innervalue;
$(something).each(function() {
innervalue= $(this).val();
console.log(innervalue);
if (innervalue.length > 0){return innervalue};
});
console.log(innervalue);